How to write a function that will set the value of a variable inside the parent object?

I created the following object:

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

However, when I call app.state.message.set ('abc'), I get an undefined error message. Can someone tell me how can I do this job? Is there a way to set the parent object?

+4
source share
4 answers
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
source
    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,
    }
}

This is a problem with volume. Change your "message" to "this". Within the functions in the message object, the method method has the value undefined.

0
source

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

Source: https://habr.com/ru/post/1544022/


All Articles