我想要实现这样一个效果:
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
https://.com/q/10...
感觉你在给自己找不自在,换个思路吧。
首先,两个函数没有相互关系,完全可以分开执行啊
其次,就算想要有关联,为什么就要2在1里面呢,能不能1在2里面?
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(...);
function f() {
console.log(1);
}
f = (function(old) {
return function() {
console.log(2);
old();
}
})(f);
f();