簡體   English   中英

對象內的NodeJS匿名函數

[英]NodeJS anonymous function within an object

為什么以下內容不返回“ a和b”?

Staff.config = {
    a: 'a constant',
    b: (function(){
        return this.a + ' and b';
    })()
};

console.log(Staff.config) // { a: 'a constant', b: 'undefined and b' }

(function(){ return this.a + ' and b'; })()在全局范圍內執行(這是指瀏覽器中的窗口),在您的情況下,全局上下文沒有屬性a因此未定義。

更簡單的解決方案是將function expression用作b的值,因此Staff.config.b()將返回預期的輸出。

 var Staff = {}; Staff.config = { a: 'a constant', b: function() { return this.a + ' and b'; } }; alert(Staff.config.b()); 

您可以使用獲取特定屬性值的getter來實現相同的目的

嘗試這個:

 var Staff = {}; Staff.config = { a: 'a constant', get b() { return this.a + ' and b'; } }; alert(Staff.config.b); 

不確定的原因與提升對象屬性的位置有關。 首先,您要嘗試引用尚未在內存中分配的對象屬性,因此Javascript無法指向內存地址,因為該內存地址尚未分配。 這就是為什么您在

return this.a + ' and b';

這里this是引用到window對象,這是一個全局對象。 如果Javascript在瀏覽器中運行,則在Javascript中,每個對象都是從全局Objectwindow擴展的。

其次,您嘗試使用Self Invoking method調用函數,但這始終在其自己的作用域中運行,這意味着您不能訪問超出其自身作用域的變量,至少如果不將其包裝到其自身上下文中也是如此。 。 就像是:

(function(closer) {
//...
})(scope)

這就是所謂的閉包。

回到您原來的問題。 如果以以下方式構造對象,則它將起作用。 這是因為您指的是已經實例化的對象的屬性。

var Staff = Staff || {};

Staff.config = function() {
  this.a = "a constant";
  this.b = this.a + " and b";    
}

var staff = new Staff.config();
console.log(staff);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM