如何自动执行包装方法

How do I automate wrapping methods?

本文关键字:方法 包装 执行 何自动      更新时间:2023-09-26

我想用函数自动将所有方法包装在一个对象中。目前,我只知道如何一一做:

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,除非你真的知道你在做什么!(你可能没有!此示例仅用于演示目的。

我找到了方法!: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");​