Best approach to avoid javascript's “this” mis

2019-02-17 16:13发布

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.

2条回答
一纸荒年 Trace。
2楼-- · 2019-02-17 16:45

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

查看更多
冷血范
3楼-- · 2019-02-17 17:02

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.

查看更多
登录 后发表回答