繁体   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