Best way to avoid javascript "this" errors

In some cases, the keyword thismay not refer to the object that I expect. (recent example: in a key event, in my XBL)

What is the best approach to avoid this error?

Currently, I always use $.fnfrom jQuery to store my variables, but I'm not sure if this is the best approach.

+5
source share
2 answers

Do not use this. Just use it correctly. Javascript is a prototype-based object-oriented language. If you create your objects using a prototype of an object, you should always know what that means.

jQuery.fn - , jQuery.prototype. jQuery.fn - . , instanceof.

this instanceof jQuery

apply call. .

.

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

.

, this, .

+3

, this , , , .

, , / .

"".

+10

All Articles