I'm defining a '*class*' in JavaScript by means of prototype.
The first time func() runs, it works, but when it's called the second time, through a setTimeout, it fails because this time it has lost the object context, I.E. *this* doesn't reference the object anymore but now references *window*.
Is there a way I can overcome this while still using prototype? or do I need instead to use closures to define a '*class*'?
function klass(){}
klass.prototype = {
a: function() {
console.log( "Hi" );
},
func: function(){
this.a();
setTimeout( this.func, 100 );
}
};
var x = new klass();
x.func();
Just fyi functions don't have any context on their own, it is resolved every time the function is called and only for that call. So it doesn't matter where and how the function is defined, it only matters how the function is called at a particular time. x.func() the function is called as a property of x. var y = {func: x.func}; y.func() the function is called as a property of y and the this is y for that call. See where I am going with this? setTimeout always calls the function with window set to this.
以上就是Passing a prototype's function as parameter without losing the 'this' context的详细内容,更多请关注web前端其它相关文章!