我想用一個函數自動將所有方法包裝在一個對象中。 現在,我只知道如何通過一個做一個:如何自動化包裝方法?
的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吸得更少的庫。我只是使用內置的原型,因爲它只是一個簡短的例子。 –