bind方法在Javascript中的工作原理

bind方法在Javascript中的工作原理,javascript,this,Javascript,This,我读了这篇文章 在最后一个示例中,他提供了代码: var first_object = { num: 42 }; var second_object = { num: 24 }; function multiply(mult) { return this.num * mult; } Function.prototype.bind = function (obj) { //console.log(this); -> TypeError: Object #&

我读了这篇文章

在最后一个示例中,他提供了代码:

var first_object = {
    num: 42
};
var second_object = {
    num: 24
};

function multiply(mult) {
    return this.num * mult;
}

Function.prototype.bind = function (obj) {
    //console.log(this); -> TypeError: Object #<Object> has no method 'log'
    var method = this,
        temp = function () {
            //console.log(this); -> RangeError: Maximum call stack size exceeded
            return method.apply(obj, arguments);
        };

    return temp;
}

var first_multiply = multiply.bind(first_object);
console.log(first_multiply(5)); // returns 42 * 5

var second_multiply = multiply.bind(second_object);
console.log(second_multiply(5)); // returns 24 * 5
var-first\u对象={
总数:42
};
变量第二个对象={
数字:24
};
函数乘法(mult){
返回此.num*mult;
}
Function.prototype.bind=函数(obj){
//console.log(this);->TypeError:Object#没有方法“log”
var方法=此,
温度=函数(){
//console.log(this);->RangeError:超过最大调用堆栈大小
返回方法.apply(对象、参数);
};
返回温度;
}
var first\u multiply=multiply.bind(第一个对象);
console.log(第一次乘法(5));//返回42*5
var second\u multiply=multiply.bind(second\u对象);
console.log(第二次乘法(5));//返回24*5
虽然他解释了,但有几件事我还是不明白

首先,为什么我们需要做
method=this
,为什么
this
引用这里的乘法函数,为什么
在下一行创建函数temp时,this
会改变?第二,为什么我们需要在这里创建函数temp?第三,我尝试使用console.log()打印出这个。奇怪的是他们都有错误,你能告诉我为什么吗

PS:我使用了WebStorm IDE


更新:请不要忽略第三个问题,为什么在使用console.log时会出现两个错误,感谢

对于常规函数,在JavaScript中,决定这个将是什么的是它的调用方式。所以它可能是任何东西

例如:

  • 将其称为obj的属性,对象是“this”
    • var obj={run:multiply};obj.run()/“this”将是“obj”
  • 直拨
    • multiply();//“this”将是全局上下文,或在严格模式下为null
  • 使用
    调用
    应用
    • multiply.call(某物,5);//“这”是“某种东西”
但是,请将此与其包含函数保持相同

Function.prototype.bind = function (obj) {
    return () => {
        return this.apply(obj, arguments);
    };
}
此外,在这两种情况下都不需要临时函数。您可以直接内联
temp
变量。

var method=this

如果写的话可能会更清楚:

var bindObj=此

绑定函数实际上是指定要乘哪个对象的函数

Function.prototype.bind = function (obj) {
    return () => {
        return this.apply(obj, arguments);
    };
}

查找JavaScript Mixin可能有助于解释更多。

可能不是一个精确的重复,但仍然有用:In
method=this
的可能重复,this是来自
foo.bind(…)
foo
,因此它是我们正在调用的
.bind
方法。我们不能在
temp
内部称之为
this
,因为
temp
this
可能是不同的(例如,如果我们做
o.bar=foo.bind(…)
,那么
temp
->
o.bar
中的
this
就是
o
)。我们需要
temp
,因为
.bind
应该返回一个函数,所以我们需要一些函数来返回。请注意,
temp
是一个糟糕的标识符名称选择。进一步看一下这里的示例,这个
.bind
实现看起来并不好,因为它不支持
.bind
中的
2+
参数,未正确设置原型链/根本未设置原型链,并且在对其进行跟踪之前,未首先检查是否已实现
.bind
。至于
console.log
失败的原因,我不能说。可能是您的IDE,请改为在浏览器中尝试。这不好。不能将箭头函数用于
new
,因此绑定构造函数将失败。你的原型在哪里?
2+
arg支持在哪里?@PaulS。我想你误解了这个问题和我的意图。OP没有询问如何实现
功能。正确绑定
。他们正在询问
这个
是如何工作的。这就是我在回答中所说的。我决不是建议OP将该代码用作多边形填充。