我想用函数自动将所有方法包装在一个对象中。目前,我只知道如何做到这一点:
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!(您可能不知道!)此示例仅用于演示目的。