this in JavaScript

  Peter        2012-05-05 12:47:37       6,041        0    

this is a keyword in JavaScript. It refers to an internal object created automatically when a function executes, it can only be used in a function. For example:
        function test(){

    this.x = 1;

  }

The this keyword will change when a function is called in different situations. However, the general rule is : this refers to the object which calls the function.

Next we discuss the use of this in 4 different situations.

1. In pure function call

This is the most common use of a function, it is a global call, so the this will refer to global object Global.

Look at following code snippet, the result is 1.

       function test(){

    this.x = 1;

    alert(this.x);

  }

  test(); // 1

To prove this is a global object, we modify the above code.

        var x = 1;

  function test(){

    alert(this.x);

  }

  test(); // 1

The execution result is 1. We modify it again.

       var x = 1;

  function test(){

    this.x = 0;

  }

  test();

  alert(x); //0

2. In an object method call

A function can be called as an object method. Then this will refer to the object calls the method.

       function test(){

    alert(this.x);

  }

  var o = {};

  o.x = 1;

  o.m = test;

  o.m(); // 1

3. In a constructor function call

As a constructor function, i.e creating an object by calling the function, then this will refer to the new object.

    function test(){

    this.x = 1;

  }

  var o = new test();

  alert(o.x); // 1

the result is 1. To prove that this is not a global object, we modify the above code.

       var x = 2;

  function test(){

    this.x = 1;

  }

  var o = new test();

  alert(x); //2

the result is 2. It means the global variable x is not changed, so this is not the global object.

4. In apply() call

With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object. The first argument for this function is the this object in the called method.

        var x = 0;

  function test(){

    alert(this.x);

  }

  var o={};

  o.x = 1;

  o.m = test;

  o.m.apply(); //0

If there is no parameter to apply(), then the this will be the global object by default. Hence, the result is 0. To prove this refers to the global object. We modify the last line.

o.m.apply(o); //1

now the result is 1. this refers to o now.

So when we use this in a function call, we must pay much attention to it, it's very easy for us to make mistake here.

Original author : 阮一峰 Source : http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html

THIS  KEYWORD  USE  JAVASCRIPT 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Theory and practice in action