【问题标题】:Function.prototype.call does not invoke method with provided context [duplicate]Function.prototype.call 不使用提供的上下文调用方法[重复]
【发布时间】:2017-11-29 18:43:37
【问题描述】:
var userData = {
    id: 2,
    name: 'Tim'
}

function Userdata( id, name) {
    this.id = id;
    this.name = name;
    this.getData = () => { 
        console.log('Name: ' + this.name + ' and Id ' + this.id ) 
      }
}

var ud = new Userdata(1, 'Tom');
ud.getData.call(userData);

输出:姓名:Tom 和 Id 1(为什么)

虽然 ud.getData.call(userData) 会在调用函数时将 this 设置为 userData,但这并没有发生。

repl here

【问题讨论】:

    标签: javascript function.prototype


    【解决方案1】:

    箭头函数没有自己的this,它们总是关闭定义它们的this,因此它们将忽略它们指定的任何this '被调用(无论是通过call 还是apply)。

    【讨论】:

    • 所以这是一种使用 es6 新语法的错误修复(关于上下文绑定)?还是其他特殊原因?
    • @ManasviSareen:这是箭头函数的目的,可以轻松创建一个关闭 this(以及 argumentssuper)的函数,而不是为它们自己绑定.如果您不想要该功能,请改用function 或方法语法。 (方法语法不适用于您的代码 sn-p。)
    【解决方案2】:

    使用常规函数:

    var userData = {
      id: 2,
      name: 'Tim'
    }
    
    function Userdata(id, name) {
      this.id = id;
      this.name = name;
      this.getData = function() {
        console.log('Name: ' + this.name + ' and Id ' + this.id)
      };
    }
    
    var ud = new Userdata(1, 'Tom');
    ud.getData.call(userData);

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2017-09-26
      相关资源
      最近更新 更多