var test = "window's test";
var foo = function(){
var test ="foo's test";
alert(this == window); // false,这里的this 指向new关键字生成的对象;
alert(this.test); // undefined;
return function(){
var test = "foo's inner test";
alert(this == window); // true ,this 指向调用该匿名函数的对象,即window对象;
alert(this.test); // "window's test";
}
}
var t = new foo();
t(); // 等价于 window.t();
var bar = {
test : "bar's test",
method: function(){
alert(this == window); // false,这里的this 指bar;
return this.test; // "bar's test";
}
}
bar.method(); // false , "bar's test";
总结:
this始终指向调用this所在函数的对象
本文通过具体示例深入探讨了JavaScript中this关键字的行为特征及其在不同上下文中的指向变化,包括函数调用、对象方法调用及构造函数调用等场景。

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



