2013-05-16 30 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