避免javascript的"this"的最佳方法错误 [英] Best approach to avoid javascript's "this" mistakes

查看:51
本文介绍了避免javascript的"this"的最佳方法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下, this 关键字可能未引用我期望的对象.(最近的示例:在关键事件中,在我的XBL中)

In some cases, the this keyword may not refer to the object I expect it to. (recent example: in an key event, in my XBL)

避免这种错误的最佳方法是什么?

What's the best approach to avoid this kind of mistake?

就目前而言,我一直使用jQuery中的 $.fn 来存储我的变量,但是我不确定这是否是最好的方法.

For now, I'm using always the $.fn from jQuery to store my variables, but I'm not sure if it's the best approach.

推荐答案

请避免使用 this .只是以正确的方式使用它.Javascript是一种基于原型的面向对象语言.如果您使用对象原型创建对象,则应该始终知道它指的是什么.

Don't avoid using this. Just use it the right way. Javascript is a prototype based object oriented language. If you create your objects using the object prototype should always know what this refers to.

jQuery.fn与 jQuery.prototype 相同. jQuery.fn 只是一个别名.您也可以使用instanceof检查this关键字.

jQuery.fn is the same thing as jQuery.prototype. jQuery.fn is just an alias. You can also check the this keyword using instanceof.

this instanceof jQuery

另一种常见的做法是在那时使用 apply call 函数方法来调用方法并绑定上下文.这将保证函数的 this 上下文.

Another common practice is to call a method and bind the context at that time using the apply or call function methods. This will guarantee the function's this context.

这是一个简单的例子.

var div = document.getElementById('div1');
function sayId(){
    alert(this.id);
}
sayId.call(div); // alerts div1

调用方法的第一个参数绑定 this 上下文并运行该函数.

The first argument of the call method binds the this context and runs the function.

知道如何控制检查 是避免常见错误的最佳方法.

Knowing how to control and check this is the best way to avoid common mistakes.

这篇关于避免javascript的"this"的最佳方法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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