簡體   English   中英

在構造函數 function 中訪問包含的 object

[英]Access the containing object in a constructor function

我想在調用包含在 object 中的 function 作為構造函數時訪問父 object。 看這個例子:

var users = {
    // The count of users
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateUser: function (name, email) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        users.count++;
    },

    getCount: function () {
        return this.count;
    },
};

如果我嘗試調用CreateUser function 作為構造函數,那么this將是對new運算符創建的空白 object 的引用。 看到這個:

var user = new users.CreateUser('Rick', 'rick@example.com')

在這種情況下,如何在不明確提及的情況下訪問包含 object 的users

將其作為顯式參數傳遞。

var users = {
    count: 0,
    _this: this,

    // Constructor function
    CreateUser: function (name, email, parent) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        parent.count++;
    },

    getCount: function () {
        return this.count;
    },
};

var user = new users.CreateUser('Rick', 'rick@example.com', users);

看起來您正在尋找的是一個static 屬性,它仍將出現在 JS 中。
雖然這是一個實驗性功能。

目前:

Static(類端)數據屬性和原型數據屬性必須在 ClassBody 聲明之外定義:

Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;

由於您在這里所做的在某種程度上類似於Joshua Bloch 的 static 工廠方法工廠方法模式的想法,因此將new關鍵字移至用戶object 的CreateUser方法是有意義的。
通過這樣做,您可以使用閉包保存對用戶object 的引用,實現嵌套構造函數 function 並使用new關鍵字調用它。

工作示例:

 var users = { count: 0, CreateUser: function (name, email) { var self = this; const createUser = function(name, email) { this.name = name; this.email = email; self.count++; } return new createUser(name, email) }, getCount: function () { return this.count; }, }; var user = users.CreateUser('Rick', 'rick@example.com') console.log(user) console.log(users.getCount()) users.CreateUser('Morty', 'morty@example.com') users.CreateUser('Jerry', 'apples@example.com') console.log(users.getCount())

暫無
暫無

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

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