0
var Foo = (function(){

    function Foo(){
        this._s="string";
        this.setButton();
    };

    Foo.prototype.setButton = function(){
document.getElementById('id').addEventListener('click', function(event) {
        alert(this._s);
    });
};

    Foo.prototype.method = function(){
        alert(this._s);
    }; 

    return Foo;

})();

var fo = new Foo();
fo.method();

I want to bind an event to a button, and execute a function whic use a 'private' var, when I click the button the function is correctly called but it can't see the var this._s (it writes 'undefined'). If I write fo.method() the string is correctly printed. here is the jsfiddle: http://jsfiddle.net/wLm1v4La/1/

AR89
  • 3,548
  • 7
  • 31
  • 46

1 Answers1

2

you have to set the context(this) of the function manually before passing it.

 Foo.prototype.setButton = function () {
   var tmpFunc = function(evt){ alert(this._s); } //store the function
   var boundFunction = tmpFunc.bind(this); //set the context manually
   //pass the function now to eventlistener
   document.getElementById('id').addEventListener('click',boundFunction);
 };
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
  • 1
    Your solution works, 'this' is Javascript is very tricky. – AR89 Oct 28 '14 at 09:57
  • It's not referring to the global object (window), try doing `alert(this);` and it will show you the button element. I believe the default is that `this` refers to the elements that the event is registered to – musefan Oct 28 '14 at 10:22