0

I have javascript class defined like this:

function C_page() {
    this.errors = [];

    function void_log_str(L_message) {
        this.errors.push(L_message);
    }

    //and more code...
}

Problem is that void_log_str scope is used as this. Is there any way to go to top-level this instead?

5 Answers5

0
function C_page() {
    this.errors = [];
    var that = this;

    function void_log_str(L_message) {
        that.errors.push(L_message);
    }

    //and more code...
}

I would do something like that.

ius
  • 1,511
  • 2
  • 15
  • 31
0

You could use scoping "var _this = this;" and then refer to _this in the function body. Or you could "bind" the function to this, e.g. using Function.prototype.bind (or a polyfill if your browser doesn't have this)

kzahel
  • 2,765
  • 1
  • 22
  • 31
0

You can use call() or apply() each time you call your function, to choose which value you want this to have;

function C_page() {
    this.errors = [];

    function void_log_str(L_message) {
        this.errors.push(L_message);
    }

    void_log_str.call(this, "value_of_l_message");
}

... or you can use bind() to force the value of this (benefits of this is that you do this in the definition, not in the invokation);

function C_page() {
    this.errors = [];

    var void_log_str = function(L_message) {
        this.errors.push(L_message);
    }.bind(this);


    void_log_str("value of l message");
    //and more code...
}

... or you can use the var that = this approach;

function C_page() {
    var that = this;
    this.errors = [];

    function void_log_str(L_message) {
        that.errors.push(L_message);
    }

    void_log_str("value of l message");
    //and more code...
}
Matt
  • 74,352
  • 26
  • 153
  • 180
0

This will work:

function C_page() {
    var context = this;
    this.errors = [];

    function void_log_str(L_message) {
        context.errors.push(L_message);
    }

    //and more code...
}
Harvey A. Ramer
  • 763
  • 7
  • 13
0

Don't use the this context which changes depending on how the function was called, but a variable in scope that directly references the array:

function C_page() {
    var errors = this.errors = [];

    function void_log_str(L_message) {
        errors.push(L_message);
    }

    //and more code...
}

You also might use bind:

function C_page() {
    this.errors = [];

    var int_log_str = Array.prototype.push.bind(this.errors);

    //and more code...
}

See also How to access the correct `this` context inside a callback? for more ways to handle this.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375