Sunday, 10 December 2017

oop - Preserve 'this' reference in javascript prototype event handler





What is the correct way to preserve a this
javascript reference in an event handler stored inside the object's prototype? I'd like
to stay away from creating temp vars like '_this' or 'that' and I can't use a framework
like jQuery. I saw a lot of people talk about using a 'bind' function but was unsure of
how to implement it in my given
scenario.




var Example =
function(foo,bar){
this.foo = foo;
this.bar =
bar;
};
Example.prototype.SetEvent = function(){

this.bar.onclick = this.ClickEvent;
};
Example.prototype.ClickEvent
= function(){
console.log(this.foo); // logs undefined because 'this' is
really 'this.bar'

};


Answer




I find bind() being
the cleanest solution so
far:



this.bar.onclick =
this.ClickEvent.bind(this);


BTW
the other this is called
that by convention very often.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...