[英]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 中。
虽然这是一个实验性功能。
目前:
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.