简体   繁体   中英

Access the containing object in a constructor function

I want to access the parent object when calling a function contained inside that object as a constructor. See this example:

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;
    },
};

If I try to invoke the CreateUser function as a constructor, then this will be a reference to the blank object that the new operator created. See this:

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

How can I access the users containing object in this case without explicitly referring to it?

Pass it as an explicit parameter.

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);

It looks like what you are looking for is a static property , which are still to come in JS.
It is an experimental feature though.

Currently:

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

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

Since what you do here is somehow similar to Joshua Bloch's idea of a static factory method or factory method pattern in general, it makes sense to move new keyword up to CreateUser method of users object.
By doing so you can use closure to save the reference to users object, implement nested constructor function and invoke it with new keyword.

Working example:

 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM