在 javascript 原型事件处理程序中保留“this"引用 [英] Preserve 'this' reference in javascript prototype event handler

查看:28
本文介绍了在 javascript 原型事件处理程序中保留“this"引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在存储在对象原型内的事件处理程序中保留 this javascript 引用的正确方法是什么?我想远离创建像_this"或that"这样的临时变量,而且我不能使用像 jQuery 这样的框架.我看到很多人谈论使用绑定"功能,但不确定如何在我给定的场景中实现它.

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'
};

推荐答案

我发现 bind() 是迄今为止最干净的解决方案:

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

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

顺便说一句,other this 通常被称为 that.

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

这篇关于在 javascript 原型事件处理程序中保留“this"引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆