2010-08-12 91 views
2
(function($) 
{ 
$.vari = "$.vari"; 
$.fn.vari = "$.fn.vari"; 

// $.fn is the object we add our custom functions to 
$.fn.DoSomethingLocal = function() 
{ 
    return this.each(function() 
    { 
     alert(this.vari); // would output `undefined` 
     alert($(this).vari); // would output `$.fn.vari` 
    }); 
}; 
})(jQuery); 

// $ is the main jQuery object, we can attach a global function to it 
$.DoSomethingGlobal = function() 
{ 
    alert("Do Something Globally, where `this.vari` = " + this.vari); 
}; 

$(document).ready(function() 
{ 
    $("div").DoSomethingLocal(); 
    $.DoSomethingGlobal(); 
}); 

我很困惑,为什么在$.fn.DoSomethingLocal功能,$(this).vari是字符串“$ .fn.vari”,而不是“$ .vari”混淆。我认为each调用中的this参考提供了一个dom对象,因此调用$(this)将返回一个标准jquery对象,其原型为$,而不是$.fn通过引用

这是怎么发生的?

+0

不知道这是否是你问的,但你是否知道.each循环内的$(this)引用循环中的当前项? – treeface 2010-08-12 20:02:24

回答

3

jQuery.fn命名空间由jQuery对象继承。所以如果你写$.fn.somewhat你现在可以通过$().somewhat访问这个。这就是为什么任何jQuery插件必须扩展jQuery.fn对象/名称空间的原因。

模式jQuery.somewhat只会扩展普通对象somewhat。这与window.somewhatanyobject.somewhat一样好。

$.fn有一个原型继承,这是所有的魔法。

return this.each(function() 
{ 
    alert(this.vari); // would output `undefined` 
    alert($(this).vari); // would output `$.fn.vari` 
}); 

在这方面,this总是指调用的对象,也就是,一个jQuery object。由于所有jQuery对象都继承自jQuery.fn,因此您在此处获得$.fn.vari

$.fn范围,this引用到jQuery对象

.each()范围,this引用到DOM节点

为什么?

Javascript的.apply()函数允许您指定要执行函数的上下文。该原则被“Resig &男孩”用于“去领”this

+1

+1正如我所了解的代码,'jQuery.fn'是对'jQuery.prototype'的引用。 http://github.com/jquery/jquery/blob/master/src/core.js#L61 – user113716 2010-08-12 20:07:02

0

当使用.each()迭代jquery对象时,这会引用未包装在jquery对象中的元素。 jQuery.vari()方法位于jquery对象上,而不是元素,因此在调用$ .vari()方法之前,必须将元素包装到jquery对象中。