-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!(您可能不知道!)此示例仅用于演示目的。

4

1 回答 1

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");​
于 2012-05-31T16:09:28.013 回答