Javascript 如何使包装方法自动化?

Javascript 如何使包装方法自动化?,javascript,Javascript,我想用一个函数自动将所有方法包装到一个对象中。 现在,我只知道如何一个接一个地做: jsfiddle: 代码: 同侧足 同侧足 同侧足 同侧足 同侧足 同侧足 ​ //仅对元素有效的方法: Element.prototype.css=函数(a,i,n){for(n in'+a==a|a)this.style[n]=a[n];返回i|n?(this.style[a]=i,this):getComputedStyle(this)[a]}; //在其周围放置一个包装,使其与节点列表一起工作 Node

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

jsfiddle:

代码:


同侧足
同侧足
同侧足
同侧足
同侧足
同侧足
​
//仅对元素有效的方法:
Element.prototype.css=函数(a,i,n){for(n in'+a==a|a)this.style[n]=a[n];返回i|n?(this.style[a]=i,this):getComputedStyle(this)[a]};
//在其周围放置一个包装,使其与节点列表一起工作
NodeList.prototype.css=函数(a,i){for(varn在此)this[n].css(a,i)};
//在其周围放置一个包装器,使其与字符串中的选择器一起工作
String.prototype.css=函数(a,i){document.querySelectorAll(this.css(a,i)}​;
//使用以下方法:
“div>i”.css(“颜色”、“红色”)​;​
我想为对象中的每个方法自动执行此操作。(单个函数自动包装每个方法)

免责声明:除非您真的知道自己在做什么,否则不要乱搞dom!(您可能不知道!)此示例仅用于演示目的。

我找到了如何执行此操作的方法!:


请注意,扩展
元素.prototype
节点列表.prototype
被认为是一种非常糟糕的做法,在浏览器之间存在巨大的不一致性。这就是为什么jQuery等现代库要求您在对这些对象使用方法之前,先用
$()
包装这些对象。这是一篇关于扩展DOM的缺点的好文章。也就是说,我真的不明白你的问题。@Mattias Buelens请注意,我不在乎这个。我这样做是为了好玩,我永远不会把它用于客户机工作:)我基本上是在尝试制作一个库,让dom不那么糟糕。我只是使用内置的原型,因为它提供了一个较短的示例。@williammalo好吧。也许你应该在你的问题中澄清这一点,否则一些新手可能会认为这是一个好主意。现在,你能解释一下“用一个函数将所有方法包装在一个对象中”是什么意思吗?@williammalo在
Element.prototype.css
NodeList.prototype.css
之间没有关系,它们只是不同的方法。每个实现都定义了
css
方法如何为这个特定类工作,幸运的是,它们可以重用以前定义的其他类的
css
方法。所以我真的不知道自动将它们包装到一个功能更强的函数中是什么意思。哦,所以你想用其他名称定义更多的方法,这些名称以类似于
元素的方式映射到该方法的
版本。现在我明白了。如果您提供了一个以上此类方法的示例,例如
css
width
height
方法,可能会更容易。这样,我们可能会注意到您想要自动化的相似之处。
<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>
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");​