绑定方法如何在Javascript中工作

时间:2015-12-04 17:20:41

标签: javascript this

我读过这篇文章http://web.archive.org/web/20110725013125/http://www.digital-web.com/articles/scope_in_javascript/

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

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

虽然他解释过,但我仍然不理解几件事。

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

PS:我使用的是WebStorm IDE。

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

2 个答案:

答案 0 :(得分:0)

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

例如:

  • 将其称为obj的属性,对象是“this”
    • var obj = {run: multiply}; obj.run() // "this" will be "obj"
  • 直接打电话
    • multiply(); // "this" will be the global context, or null in strict mode
  • 使用callapply
    • multiply.call(something, 5); // "this" is "something"
但是,

Fat arrow functions与其包含的函数保持相同的this

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

此外,在任何一种情况下都不需要临时功能。您可以内联temp变量。

答案 1 :(得分:0)

var method = this;

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

var bindObj = this;

bind函数实际上是指定哪个对象乘以函数。

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

相关问题