this在js里设计得还真是够复杂,或者确切地说根本就是设计错了(这不是我说的,是写那本the good parts的老大说的)。
一个例子:
1 2 3 4 5 6 7 | myObject.double = function () { var helper = function () { this.value = add(this.value, this.value); }; helper(); }; |
这个方法要做的事情很简单,就是把自己的value属性double一下。一切看起来都很完美,直到真正跑起来,你才会发现报错说value没定义。
原因在于那个内部匿名函数里的this并不是myObject,而是这个函数本身!诡异得很。
解决起来倒是简单:
1 2 3 4 5 6 7 8 9 | myObject.double = function () { var that = this; var helper = function () { that.value = add(that.value, that.value); }; helper(); }; |
习惯上大家都用that。怪不得之前总是看到that这that那的,还以为是js的保留字。