【问题标题】:Why should fix 'this' when return a function?返回函数时为什么要修复“this”?
【发布时间】:2015-12-01 10:51:07
【问题描述】:

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

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

执行时 beforefn.apply(this,arguments);andreturn _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; } }

【问题讨论】:

  • 你是什么意思,“没有解决这个问题”?你能说明你将如何重写before 方法吗?
  • var foo = "test" 在你的test 函数中应该做什么?它从未使用过。
  • @Bergi 是的,没用,我删了
  • @Bergi 感谢提醒,我已经重写了我的问题中的鳕鱼。
  • 嗯,return arguments.callee(除了被弃用)不再调用原始函数_self了吗?

标签: javascript return closures this


【解决方案1】:

.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 仍然需要向函数传递可变数量的参数。

【讨论】:

  • 非常感谢,伙计,我对 apply() 感到困惑,但现在我明白了。再次感谢!
  • 很高兴有帮助,请考虑accepting the answer
猜你喜欢
  • 1970-01-01
  • 2017-07-08
  • 2016-04-06
  • 2016-03-18
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 2020-11-25
  • 2011-05-22
相关资源
最近更新 更多