I have the following code, which seems to override the jQuery.error function:
$.test = function(){
var test = this;
test.error = function(){
console.log('Why is this function getting called');
};
};
$(document).ready(function(){
var someObj = $.test();
$.error();
});
This code will output ‘Why is this function getting called’ in the console.
However, if I change my code slightly, the native jQuery error function is called:
$(document).ready(function(){
var someObj = new $.test();
$.error();
});
It seems that in the first example, ‘this’ refers to jQuery, but in the second example it refers to someObj. Why is this?
Your method
$.testis a new property on the$object. So it makes sense that thethisobject inside that method — the scope of the method — is object to which the property belongs.An example without jQuery (on fiddle here: http://jsfiddle.net/kxncT/):
However, when you call the
newoperator, you’re invoking a constructor. In that case, a new scope is created for the new object. So if in the above example you callnew a.method(), the alert will readfalse, because the new scope that’s created is new, and unrelated to the parent object.In writing this answer, I’ve tried to paraphrase what I read in this blog post: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
The post is much better than my answer, and if there are any discrepancies, trust the post 🙂