this.someFunction.call(this, param); 的目的是什么?

What is the purpose of this.someFunction.call(this, param);

我在很多地方都遇到过一些具有这种模式的代码:

this.someFunction.call(this, param);

但在我看来,这只是一种更冗长的输入方式

this.someFunction(param)

该模式有时会出现在作为回调提供的函数内。它恰好使用 Backbone,以防相关。像这样:

Backbone.View.extend({
    // other stuff ...

    someFunction: function(param) {
        // ...
    },
    anotherFunction: function() {
        this.collection.on("some_event", function() {
            this.someFunction.call(this, param);
        });
    }
});

该模式是否实际具有与 this.someFunction(param) 不同的效果,或者有人只是担心闭包没有捕获正确的 this

感谢您的任何见解!

我看不出有任何理由在您提供的代码中使用这种函数调用方式。这里最好使用像这样的直接函数调用(如果你不需要修改参数)

this.collection.on("some_event", this.someFunction, this); 

this.collection.on("some_event", function() {
    this.someFunction(//some modified args)
}, this); 

让我提供 .call 正确用法的示例。你肯定看过这个:

Array.prototype.slice.call(arguments, 2); 

由于arguments不是数组,我们可以用'borrow'数组的方法对arguments进行操作。如果您尝试在 arguments 上调用 slice,您将得到一个错误

Does the pattern actually have an effect that isn't the equivalent of this.someFunction(param)?

不对,确实是一样的。假设 this.someFunction 是一个从 Function.prototype 继承 .call 的函数(但这是吹毛求疵)。

看起来有人过于谨慎了,或者代码是没有使用 this 两次的东西的遗留物。或者也许作者知道 this-context-in-callbacks issue 但未能正确处理它。