[英]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.