[英]How to access constructor function from object by using this
在這個例子中。 我需要從對象功能更新好友列表。
var MyClass = function () {
this.friends = [];
this.runtime = {
add: function (name) {
this.friends.push(name);
}
}
};
MyClass.prototype.AddFriend = function (name) {
this.runtime.add(name);
};
MyClass.prototype.GetFriends = function () {
return this.friends;
};
怎么可能?
就像我在評論中說,這讓使用更感this.friends.push(name)
,但如果你真的要使用奇運行功能,那么你需要的副本保存this
到一個新的變量:
var MyClass = function () {
var _this = this;
this.friends = [];
this.runtime = {
add: function (name) {
_this.friends.push(name);
}
}
};
您還可以使用bind()方法:
var MyClass = function () {
this.friends = [];
this.runtime = {
add: function (name) {
this.friends.push(name);
}.bind(this)
}
};
MyClass.prototype.AddFriend = function (name) {
this.runtime.add(name);
};
MyClass.prototype.GetFriends = function () {
return this.friends;
};
在此處了解更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.