Javascript 如何编写一个函数来设置父对象中变量的值?
我创建了以下对象:Javascript 如何编写一个函数来设置父对象中变量的值?,javascript,Javascript,我创建了以下对象: app.state = { message: { clear: function() { message.error = null; message.text = null; }, alert: function(text) { message.error = true; message.text = text;
app.state = {
message: {
clear: function() {
message.error = null;
message.text = null;
},
alert: function(text) {
message.error = true;
message.text = text;
},
set: function(text) {
message.error = null;
message.text = text;
},
error: null,
text: null,
}
}
然而,当我调用app.state.message.set('abc')时,我会收到一个错误消息,消息未定义。有人能告诉我怎样才能做到这一点吗?有什么方法可以设置父对象吗
app.state = {
message: {
clear: function() {
this.error = null;
this.text = null;
},
alert: function(text) {
this.error = true;
this.text = text;
},
set: function(text) {
this.error = null;
this.text = text;
},
error: null,
text: null,
}
}
这是一个范围问题。把你的“信息”改为“这个”。在消息对象的功能范围内,对象“方法”未定义。您可以使用
此
。在该上下文中,此
等于消息
app.state = {
message: {
clear: function() {
this.error = null;
this.text = null;
},
alert: function(text) {
this.error = true;
this.text = text;
},
set: function(text) {
this.error = null;
this.text = text;
},
error: null,
text: null,
}
}
您可以使用闭包:
app.state = new (function(){
var
error = null,
text = null;
this.message = {
clear: function() {
error = null;
text = null;
},
alert: function(newText) {
error = true;
text = newText;
},
set: function(newText) {
error = null;
text = newText;
},
getError: function() {
return error;
},
getText: function() {
return text;
}
};
})();
app.state = new (function(){
var
error = null,
text = null;
this.message = {
clear: function() {
error = null;
text = null;
},
alert: function(newText) {
error = true;
text = newText;
},
set: function(newText) {
error = null;
text = newText;
},
getError: function() {
return error;
},
getText: function() {
return text;
}
};
})();