[英]Javascript OOP : Explain why f.a returns something whereas f.b and c.a returns undefined
解釋為什么 fa 返回一些東西,而 fb 和 ca 返回 undefined。 不要回答:因為它就是那樣,或者你並不真正了解 javascript 並像 Feynman 所說的那樣通過 rotte 學習 ;)
function f() {
f.a = "test 1";
this.b = "test 2";
return this;
}
let c = f();
console.log(f.a);
console.log(f.b);
console.log(c.a);
fa 返回一些東西,因為在函數中你將“test 1”分配給 fa
this.b 是窗口 console.log(window.b) 將返回“test 2”
c 是您返回“this”的函數的返回值,“this”是窗口 -> 窗口的屬性 a 未定義
在你調用f
之后,它給自己(f 函數對象) a
分配給字符串"test 1"
的屬性。
因為f
不是用new
調用的,所以函數體內的this
指的是全局對象(瀏覽器中的window
,node 中的global
)。 這意味着在函數體內對this.b
的賦值等價於window.b = "test 2"
。
然后函數 f 返回this
,它是global
對象,所以c = global
。
尚未為全局對象分配屬性a
,因此ca
未定義。 但cb
將是"test 2"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.