Passing a prototype's function as parameter without losing the 'this' context

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前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏