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

标签 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 = 函数(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,则只能修复_selfthis参数,如

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/

相关文章:

javascript - JavaScript 中的闭包和 "this"关键字问题

Rust 错误 [E0373] : closure may outlive the current function, 但它借用了 `iteration_index`

javascript - NodeJs - [Restful API] 如何分离不同js文件中的app get方法?

javascript - 在 jQuery 中将下拉列表值设置为文本框

javascript - 使用 Javascript 在悬停和单击时切换 CSS 背景颜色

来自webview的android html代码

javascript - 数据库 Jquery - 使用 ScrollY 时列标题未对齐

java - 为什么 "return"在 Kotlin 中可以返回 "return"?

python - pycharm """:return :"""in a Python documentation string

python - Python 中的仿函数与函数闭包