我想用一个函数自动将所有方法包装在一个对象中。 现在,我只知道如何通过一个做一个:如何自动化包装方法?
的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! (您可能不需要!)此示例仅用于演示目的。
注意,延长'Element.prototype'和'NodeList.prototype'被认为是一个非常不好的做法与跨浏览器的巨大矛盾。这就是为什么像jQuery这样的现代库要求你在使用方法之前用'$()'包装这些对象。 –
http://perfectionkills.com/whats-wrong-with-extending-the-dom/是关于扩展DOM的缺点的一篇很好的文章。这就是说,我不太了解你的问题。 –
@Mattias Buelens请注意,我不关心这件事。我这样做是为了好玩,我永远不会把它用于客户端工作:)我基本上正在做一个使得dom吸得更少的库。我只是使用内置的原型,因为它只是一个简短的例子。 –