访问次数
我的另一个总结性博客: todototry 大米粒

javascript中的this在不同场景下的区别

javascript在初版的设计上存在失误,导致了这门语言在使用时,经验型写法并不能得到像其它几个流行语言一样预期。其中的this的使用就是一个典型。

this在javascript中是由解释器注入的,并且在我们使用不同的方法定义函数时,注入的this含义不同。以下是crokford总结的四类情况。

如果你使用闭包时总是结果不如预期,又或者返回NaN 或 undefined ,那请注意参看本文。

 

0. 构造器函数内的this:

如果函数创建的目的是使用new来调用,并产生一个对象,那么此函数被称为 构造器函数。

var Niu = function (string) {

this.name = string;

};

  

上述的Niu即为一个构造器函数,其内部的this会自动绑定到new所创建的新对象上面。

1. 对象成员方法内的this:

对象的成员方法中的this是对象本身,此时跟其它语言是一致的,但是也有差异,javascript中this到对象的绑定发生在函数调用的时候。

var myObj = {

    value: 0,

    increment: function (inc) {

          this.value += typeof inc === 'number' ? inc : 1;

    }

};

myObj.increment();    //1

myObj.increment(2);   //3

  

 

2. 普通函数 与 闭包内的this:

2.1 以普通方式定义的函数中的this:会被自动绑定到全局对象。

var value = 232;

function toStr()

{

  console.log("%d", this.value);  //232

}

  

2.2 对象方法中闭包函数的this:

 由2.1可知,在以普通方式定义的函数中的this会被自动绑定到全局对象上,大家应该可以看出闭包函数定义也与普通方式无异,因此他也会被绑定到全局对象上。

value = 10;
var closureThis = { value: 0, acc: function () { var helper = function () { this.value += 2; console.log("this.value : %d", this.value); } helper(); } }; closureThis.acc(); //12 closureThis.acc(); //14 var closureThat = { value: 0, acc: function () { that = this; var helper = function () { that.value += 2; console.log("that.value : %d", that.value); } helper(); } }; closureThat.acc(); // 2 closureThat.acc(); // 4

从上述输出值可以看出,上述描述的正确性。

3. Apply函数的参数this:

 appy方法允许我们选择一个this值作为第一个参数传递,第二个参数是一个数组,表明可以传递多个参数。

posted @ 2015-03-23 13:20  fandyst  阅读(442)  评论(0编辑  收藏  举报