如何自动执行包装方法
How do I automate wrapping methods?
我想用函数自动将所有方法包装在一个对象中。目前,我只知道如何一一做:
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");
相关文章:
- 将setTimeout()包装器实现为Element.prototype中的方法
- 将同步函数包装到承诺中的最佳方法是什么?
- 如何制作父/包装器组件“;触发器”;或调用子级上的方法
- ES6类:在另一个函数中包装方法实现
- 绑定实例方法与包装匿名函数
- 控制台.log包装器,保留行号并支持大多数方法
- 使用 Javascript 的 replace() 方法用 html 包装单词
- 好的 ECMAScript 2015 方法来包装 CasperJS
- 如何自动执行包装方法
- 在 JavaScript 中用“try catch”包装每个方法的性能问题
- 从指令包装源元素的更好方法
- Koa:在没有现有包装器的情况下连接到数据库的最明智的方法是什么?
- Meteor 方法在返回包装在回调中时不返回返回值
- jQuery中根据其数据属性包装元素的最佳方法是什么?
- 这是将readFileSync包装在承诺中的正确方法吗?
- 如果对 JSONP 请求的服务器响应未正确包装在函数中,是否有任何方法可以覆盖“无效标签”错误
- 用try-catch包装现有javascript对象的所有方法
- 保存方法结果的包装器
- sinon-spy在异步回调中不包装方法
- 将方法名称作为回调传递VS.用烦人的函数包装它