JavaScript: creating a link to 'this' (for example, "var _this = this") or bind / call / apply

Reliance on thisthe wrong context is a common lie. A contrived example:

function SomeClass() {
    this.prop = 42;
    document.body.addEventListener('click', function() {
        alert(this.prop); // will be undefined
    });
}
new SomeClass();

One way: bind(or callor apply), for example:

function SomeClass() {
    this.prop = 42;
    document.body.addEventListener('click', (function() {
        alert(this.prop); // works
    }).bind(this));
}
new SomeClass();

Another option is to make a link to thisavailable through closure, usually _thiseither self:

function SomeClass() {
    var _this = this;
    this.prop = 42;
    document.body.addEventListener('click', function() {
        alert(_this.prop); // works
    });
}
new SomeClass();

, , bind(), (, , , ), . , : ) , ) , bind , . ?

+4
2

" " :


function SomeClass() {
    this.prop = 42;
    document.body.addEventListener('click', (function() {
        alert(this.prop); // works
    }).bind(this));
}
new SomeClass();

, , , , , , ( , ., )

, , :


function SomeClass() {
    var _this = this;
    this.prop = 42;
    document.body.addEventListener('click', function() {
        alert(_this.prop); // works
    });
}
new SomeClass();

- , , ,


function SomeClass() {
    var prop = 42;
    document.body.addEventListener('click', function() {
        alert(prop); // works
    });
}
new SomeClass();

, , , , "" , , , ( ) ) / , ( , )

EDIT: wait!, this.prop = 42, , PoV , getter:


function SomeClass() {
    var prop = 42;
    document.body.addEventListener('click', function() {
        alert(prop); // works
    });
    this.getProp = function() {
      return prop;
    };

    this.setProp = function(newValue) { // prop is supposed to be modifiable ?
      prop = newValue;
    };
}
new SomeClass();

, "this", , - :


function SomeClass(receiver) {
    var prop = 42;
    receiver.addEventListener('click', function() {
        alert(prop); // works
    });
}
new SomeClass(document.body);
+3

?

, . , , bind ( ES3). , , var ( , ), , , , .

, , , .

, , JavaScript, this JavaScript. , self/bind, .

+1

All Articles