如何编写一个在父对象中设置变量值的函数?

时间:2014-06-10 16:55:55

标签: javascript

我创建了以下对象:

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')时,我收到一条错误消息,指出消息未定义。有人能告诉我如何才能做到这一点吗?有什么方法可以设置父对象吗?

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

这是一个范围问题。将您的“消息”更改为“此”。在消息对象中的函数范围内,对象“方法”未定义。

答案 2 :(得分:0)

您可以使用this。在此背景下,this等于message

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

答案 3 :(得分:0)

你可以使用闭包:

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