Why does my code replace the jQuery.error function?
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 se开发者_如何学JAVAems that in the first example, 'this' refers to jQuery, but in the second example it refers to someObj. Why is this?
Your method $.test
is a new property on the $
object. So it makes sense that the this
object 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/):
var a = {};
a.method = function() {
alert(this === a); // true
};
a.method();
However, when you call the new
operator, you're invoking a constructor. In that case, a new scope is created for the new object. So if in the above example you call new a.method()
, the alert will read false
, 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 :)
精彩评论