2013-05-16 28 views
2

我不知道是否有可能建立某种形式的建设,其中一个可以做到以下几点:JavaScript的jQuery的建筑等

$("some element").somemethod(arg),这将是完全一样的话说$.somemethod("some element", arg)

我知道这是可能的在jquery中使用例如$(selector).each(callback),这看起来相当于$.each(selector, callback)。不过,我发现很难理解jquery如何做到这一点。似乎“每个”方法定义了两次,但这是我想避免的。这可能吗?

+6

他们实际上是不等价的? '$ .fn.each = function(a,b){return $ .each(this,a,b)};' – Bergi

+0

有什么区别? – user2180613

+3

然而,它被定义了两次,'$(selector).somemethod()'版本在内部使用'$ .someMethod()'版本来保持代码是DRY。 –

回答

0

你的意思是这样的:


function $(context){ 
    this.context = context; 
    if(!(this instanceof $)) return new $(context); 
} 

$.prototype.somemethod = function(arg){ 
    // The bulk of the function is defined here, only once 
    console.log("Doing some stuff to " + this.context + " with " + arg); 
} 

$.somemethod = function(context, arg){ 
    $(context).somemethod(arg); 
} 

$('body').somemethod(7); // Doing some stuff to body with 7 
$.somemethod('body', 7); // Doing some stuff to body with 7 
3

是的,这是可能的,你必须实现自己该插件。

(function($) { 
    $.fn.somemethod = function() { 
     return this.each(function() { 
      // do something to each element here 
     }); 
    }; 
}(jQuery)); 
5

它们被定义了两次,但实际完成该工作的代码只写入一次。

$.myPlugin = function(element,text){ 
    $(element).text(text); // work is done here 
    return element; 
} 
$.fn.myPlugin(function(text) { 
    return $.myPlugin(this,text); 
}); 

这里是jQuery的核心内所使用的这样的一个例子:

https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L250