我在一本书上读过一段代码,
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 = 函数(beforefn){
var _self = 这个;
返回函数(){
beforefn(参数);
返回参数。被调用者;
}
}
最佳答案
.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
参数,如
Function.prototype.before = function(beforefn){
var fn = this;
return function() {
beforefn.apply(null, arguments);
return fn.apply(null, arguments);
}
}
其中o1.test()
将不再起作用。当然,仍然需要 apply
来向函数传递可变数量的参数。
关于javascript - 为什么返回函数时要修复 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018566/