为什么要修复 'this' 当 return 一个函数?

Why should fix 'this' when return a function?

我在书上看了一段代码,

Function.prototype.before = function(beforefn){
    var _self = this;
    return function(){
        beforefn.apply(this,arguments);
        return _self.apply(this,arguments);
    }
}

执行时 beforefn.apply(this,arguments);return _self.apply(this,arguments);,我认为即使不修复'this'也会得到相同的结果。

function test(){
    return function(){
        alert(this.foo);
    }
}
var o1 = {
    foo:"foo",
    test:test(),
}

o1.test(); //alert foo

那么作者修复这个的目的是什么? P.S第一次在Whosebug提问,见谅English.Thanks

感谢您注意到我的问题!我会这样重写:

Function.prototype.before = function(beforefn){ var _self = this; return function(){ beforefn(arguments); return arguments.callee; } }

.apply(this, …) 不会 修复 thisArg - 相反,它甚至使它成为动态的,使用返回函数中的当前动态 this。看看它的效果如何:

function test(){
   alert(this.foo);
}
var o1 = {
    foo: "bar",
    test: test.before(function() { console.log(this); })
};
o1.test(); // logs o1, alerts "bar"
o1.test.call({}); // logs the empty object, alerts undefined

如果您没有传递当前的this,您只会修复_selfthis参数,如

Function.prototype.before = function(beforefn){
    var fn = this;
    return function() {
        beforefn.apply(null, arguments);
        return fn.apply(null, arguments);
    }
}

其中 o1.test() 将不再起作用。当然,apply 仍然需要将可变数量的参数传递给函数。