开发者

Best approach to avoid javascript's "this" mistakes

开发者 https://www.devze.com 2023-02-01 12:25 出处:网络
In some cases, the this keyword may not refe开发者_C百科r to the object I expect it to. (recent example: in an key event, in my XBL)

In some cases, the this keyword may not refe开发者_C百科r 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号