2012-05-31 46 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'方法。这样,我们可能已经注意到您想要自动化的相似之处。 –