我試過了閉包並發現了意外的行爲。有人可以解釋爲什麼這個代碼以這種方式工作嗎?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