扫码关注官方订阅号
我想要实现这样一个效果:
function f = function(){ console.log(1); } f.before(function(){ console.log(2); }) f(); //我想要这里输出为:2 1
请问before函数要怎么实现?
欢迎选择我的课程,让我们一起见证您的进步~~
Function.prototype.before = function() { for (var i=0; i<arguments.length; i++) { if (typeof arguments[i] === 'function') { arguments[i]() } } this() }
在chrome的控制台测试可以达到你想要的效果,,不过可能会有兼容性问题
好像没什么意思,不过还是折腾了一下
Function.prototype.before = function() { this.beforeArrFunc = [] for (var i=0; i<arguments.length; i++) { if (typeof arguments[i] === 'function') { this.beforeArrFunc.push(arguments[i]) } } } Function.prototype.execute = function() { for (var i=0; i<this.beforeArrFunc.length; i++) { this.beforeArrFunc[i]() } this() } var a = function() { console.log(1) } a.before(function() { console.log(2) }) a.execute()
这样的缺点是,具体调用时需要另一个实例方法来辅助好处就是也可以直接调用a(),这样不会调用到before function
a()
before function
function f() { console.log(1); } f = (function(old) { return function() { console.log(2); old(); } })(f); f();
Function.prototype.before = function(beforeFn) { var self = this; return function() { beforeFn(); self.apply(this, arguments); } }; function f() { console.log(1); } var ff = f.before(function() { console.log(2); }); ff(); // Output: 2 1 // 注意使用before的返回值,f没有变化 // 或者使用 f = f.before(...);
https://segmentfault.com/q/10...
感觉你在给自己找不自在,换个思路吧。
首先,两个函数没有相互关系,完全可以分开执行啊其次,就算想要有关联,为什么就要2在1里面呢,能不能1在2里面?
ES6新增了代理功能:
function proxyFn(fn){ return new Proxy(fn, { apply: function(target, thisBinding, args){ console.log('before..'); target.apply(thisBinding, args); console.log('after..'); } }) } var aFn = proxyFn(function(v){ console.log(v); }); aFn(12); // before 12 after
有待优化....
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
在chrome的控制台测试可以达到你想要的效果,,
不过可能会有兼容性问题
更新
好像没什么意思,不过还是折腾了一下
这样的缺点是,具体调用时需要另一个实例方法来辅助
好处就是也可以直接调用
a(),这样不会调用到before functionhttps://segmentfault.com/q/10...
感觉你在给自己找不自在,换个思路吧。
首先,两个函数没有相互关系,完全可以分开执行啊
其次,就算想要有关联,为什么就要2在1里面呢,能不能1在2里面?
ES6新增了代理功能:
有待优化....