2012-05-31 43 views
-1

我想用一個函數自動將所有方法包裝在一個對象中。 現在,我只知道如何通過一個做一個:如何自動化包裝方法?

的jsfiddle:http://jsfiddle.net/4VuE7/

代碼:

<div style=white-space:pre> 
<i>foo bar lorem ipsum</i> 
<i>foo bar lorem ipsum</i> 
<i>foo bar lorem ipsum</i> 
<i>foo bar lorem ipsum</i> 
<i>foo bar lorem ipsum</i> 
<i>foo bar lorem ipsum</i> 
</div>​ 
<script> 

//method that only works on elements: 
Element.prototype.css = function(a,i,n){for(n in''+a===a||a)this.style[n]=a[n];return i||n?(this.style[a]=i,this):getComputedStyle(this)[a]}; 

//put a wrapper around it that makes it work with nodelists 
NodeList.prototype.css = function(a,i){for(var n in this)this[n].css(a,i)}; 

//put a wrapper around it so it works with a selector in a string 
String.prototype.css = function(a,i){document.querySelectorAll(this).css(a,i)}​; 

//use the method: 

"div>i".css("color","red")​;​ 

</script> 

我想爲對象中的所有方法自動執行此操作。 (一個功能自動包裝每種方法)

免責聲明:除非你真的知道你在做什麼,否則不要亂搞dom! (您可能不需要!)此示例僅用於演示目的。

+3

注意,延長'Element.prototype'和'NodeList.prototype'被認爲是一個非常不好的做法與跨瀏覽器的巨大矛盾。這就是爲什麼像jQuery這樣的現代庫要求你在使用方法之前用'$()'包裝這些對象。 –

+3

http://perfectionkills.com/whats-wrong-with-extending-the-dom/是關於擴展DOM的缺點的一篇很好的文章。這就是說,我不太瞭解你的問題。 –

+0

@Mattias Buelens請注意,我不關心這件事。我這樣做是爲了好玩,我永遠不會把它用於客戶端工作:)我基本上正在做一個使得dom吸得更少的庫。我只是使用內置的原型,因爲它只是一個簡短的例子。 –

回答

0

我發現如何做到這一點!:http://jsfiddle.net/4VuE7/3/

Element.prototype.css = function(a,i,n){ 
for(n in''+a===a||a)this.style[n]=a[n];return i||n?(this.style[a]=i,this):getComputedStyle(this)[a]}; 

Object.getOwnPropertyNames(Element.prototype).forEach(function(a){ 

    NodeList.prototype[a]=function(){for(var n in this)this[n][a].apply(this[n],arguments)} 

    String.prototype[a]=function(){document.querySelectorAll(this)[a].apply(document.querySelectorAll(this),arguments)} 

}); 


"div>i".css("color","red");​ 
+0

哦,所以你想用其他名字來定義更多的方法,這些名字的映射方式與該方法的'Element.prototype'版本類似。現在我懂了。如果您使用多種此類方法舉例說明,這可能會更容易一些,例如'css','width'和'height'方法。這樣,我們可能已經注意到您想要自動化的相似之處。 –