看《JavaScript:the good parts》一书中讲到Javascript方法调用的四种方式,其中比较难理解的是function invocation pattern ,因为其中讲到了Javascript设计的一个缺陷,原文中这么说:
When a function is not the property of an object, then it is invoked as a function:
var sum = add(3, 4); // sum is 7
When a function is invoked with this pattern, this is bound to the global object.
This was a mistake in the design of the language. Had the language been designed
correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function.因为这里没有给代码, 我理解了半天也没感觉这是个缺陷,因为我觉得当你调用add(3,4);的时候,理应this指向全局变量呀。于是我找了一些文章,大部分也都没有对此进行解释,看来大家都很聪明,没办法,自己测试一下。
代码如下:
int1 = 4;
obj = {
int1: 5,
outer: function () {
function inner() {
console.log(this.int1);
};
inner();
console.log(this.int1);
}
};
obj.outer();运行结果会是:
4
5看来确实有作者说的那个问题,即当inner();调用时,this指向的是最外层的对象,甚至都不是obj。
但有意思的是下面的一段代码:
int1 = 4;
obj = {
int1: 5,
outer: function () {
int1 = 6;
function inner() {
console.log(this.int1);
};
inner();
console.log(this.int1);
}
};
obj.outer();可以看出来这段代码对前面的修改微乎其微,只是简单增加了一句int1 = 6;但这次的运行结果是:
6
5
可见,这次调用inner();时this指向的不再是全局的变量,二十outer的变量,这忽上忽下的this指针把我搞晕了,具体的实现我还没搞懂。
本文通过两个示例探讨了JavaScript中this关键字的行为变化,尤其是在内部函数调用时this指向的不确定性,揭示了语言设计中一个鲜为人知的问题。


被折叠的 条评论
为什么被折叠?



