[英]why does `this` matter in this case?
const library = (function () { let myLibrary = [1, 2]; function get() { return this.myLibrary; } return { myLibrary, get } })(); console.log(library.get()); // [1, 2] library.myLibrary = [0]; console.log(library.get()); // [0]
const library = (function () { let myLibrary = [1, 2]; function get() { return myLibrary; } return { myLibrary, get } })(); console.log(library.get()); // [1, 2] library.myLibrary = [0]; console.log(library.get()); // [1, 2]
這些片段之間的唯一區別是這一行:
return this.myLibrary;
vs return myLibrary;
第一個是改變工廠 function 內部的數組,但第二個沒有。 但我不明白為什么第一個代碼與第二this
代碼的工作方式不同。
在第一種情況下, get
function 將返回由匿名 function 創建和返回的 object 上的myLibrary
屬性的值。
在第二種情況下, get
function 返回它關閉的myLibrary
變量的值。 該變量與 object 上的屬性完全無關,因此分配給它不會更改get
返回的變量。 為了說明這一點,這是您的第二個示例,其中myLibrary
屬性離開了 object 被返回:
const library = (function () { let myLibrary = [1, 2]; function get() { return myLibrary; } return { get } // <<================ No `myLibrary` property at all })(); console.log(library.get()); // [1, 2] <== You still get the value, even though // the property doesn't exist library.myLibrary = [0]; // <== Creates a property, which has nothing // to do with what `get` returns console.log(library.get()); // [1, 2] <== Since the property is unrelated, // there's no difference here
如果你這樣做了:
console.log(library.myLibrary);
最后,你會得到[0]
,由library.myLibrary = [0];
.
好吧,如果您的 function 不是 static 並且 myLibrary 是全局的,那么您需要使用“this”關鍵字。 這只是指非 static 全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.