返回函数时为什么要修复'this'?

时间:2015-12-01 10:51:07

标签: javascript return closures this

我在一本书中读到了这段代码,

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这是第一次在StackOverflow中提问,请原谅我糟糕的英语。谢谢

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

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

1 个答案:

答案 0 :(得分:0)

.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,则您只能修复_self this的{​​{1}}参数,如

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

o1.test()不再适用。当然,仍然需要apply来向函数传递可变数量的参数。