【问题标题】:Why does destructuring an argument object affect it's 'this' value? [duplicate]为什么解构参数对象会影响它的“this”值? [复制]
【发布时间】:2020-08-04 19:44:45
【问题描述】:

谁能告诉我为什么解构会影响对象的this 值。有很多简单的解决方法,但我只想知道这里实际发生了什么。看起来它应该可以工作,但是由于解构导致this 范围发生了一些奇怪的事情。有人知道吗?

这是一个简单的对象:

const user = {
  name: 'John',
  age: 30,
  sayHi() {
    console.log(this); // undefined for foo(), but defined for bar()
    return `hello, ${this.name}`;
  }
};

在 foo 中,我使用解构来访问对象键,但是 this 值在 sayHi() 内部是未定义的。

const foo = ({ sayHi, name }) => {
  console.log(sayHi()); // hello, [empty string]
  console.log('OUTPUT: foo ->  name', name); // John
};

foo(user);

但是在这里,只传递对象而不进行解构,可以按预期工作,并且定义了 this 值。

const bar = person => {
  console.log(person.sayHi()); // hello, John
};

bar(user);

【问题讨论】:

    标签: javascript scope this destructuring


    【解决方案1】:

    在第一种情况下,通过解构,您创建了对sayHi 函数的单独引用。然后,当您从 foo 的主体中调用它时,这将成为 thissayHi 的主体中的上下文。

    在第二种情况下,您将其称为person.sayHi,因此这种情况下的上下文是包含对象 - 即person。在sayHi 内,thisperson,并定义了名称。

    解构并没有什么神奇之处,如果你手动创建对函数的引用,你会得到同样的效果:

    const bar = person => {
      const sayHi = person.sayHi;
      console.log(sayHi()); 
    };
    

    【讨论】:

    • 啊,我现在明白了。我知道这很简单。因此,如果我想将它与对象分开,我可以使用 bind() 。谢谢!
    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2014-03-25
    相关资源
    最近更新 更多