我试过了闭包并发现了意外的行为。有人可以解释为什么这个代码以这种方式工作吗?javascript - 在外部函数中定义的访问属性
function foo() {
this.a='hello';
return {
aaa:function() {
return a; // this suprises me, how can be here accessed 'a' ?
}
}
}
o=foo();
alert(o.aaa()); // prints 'hello' ! , I expected undefined
我不明白,为什么我总是用var that=this
句话,如果有可能从内部功能直接访问功能特性。
的jsfiddle https://jsfiddle.net/5co6f707/
'this'并不总是指向同一个对象。这取决于函数如何被调用。写'var that = this'是捕获'this'引用的原始对象的一种方式,以防对象引用稍后改变。 –
'this'关键字与闭包无关吗?如果你已经使用了'var a',它就可以工作。 – Bergi