Best approach to avoid javascript's “this” mistakes

别说谁变了你拦得住时间么 提交于 2019-12-30 09:31:11

问题


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?

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.


回答1:


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 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

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.

Here is a simple example.

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

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.




回答2:


Learn how and why this behaves the way it does, then read the code you're working on.

Don't trust some magic functionality, you might always end up with unexpected results if you don't know/read the code.

There's simply no single awesome solution for this "problem".



来源:https://stackoverflow.com/questions/4520243/best-approach-to-avoid-javascripts-this-mistakes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!