JavaScript call() 和 apply() 方法及变量赋值

JavaScript call() and apply() Method and variable assignment

我目前正在使用一本书学习 JavaScript。一个例子解释了函数的双重用途。

function Person(name) {
  if (this instanceof Person) {
    this.name = name
  } else {
    throw new Error("Nutze new")
  }
}
let aPerson = new Person("Astrid"); 
// let aPerson = Person("Astrid"); // throws an error
let notAPerson = Person.apply(aPerson, ["Elmar"]);
let notAPerson2 = Person.call(aPerson, "Peter");
console.log(aPerson); //  Object { name: "Peter" }
console.log(notAPerson); //  undefined
console.log(notAPerson2); //  undefined

我知道,我可以用 apply()call() 方法设置 contex。 但我不明白,为什么变量 notAPersonnotAPerson2 未定义?

如果有人能向我解释一下就好了。

new 关键字改变函数的执行方式。当在没有 new 的情况下使用时,它完全按照它在函数体中所说的那样做。但是当你用 new 调用函数时,它的工作方式有点像这样:

function Person(name) {
  var this = {}
  if (this instanceof Person) {
    this.name = name
  } else {
    throw new Error("Nutze new")
  }
  return this
}

因此,当您使用 new 调用函数时,this 是一个全新的对象,它会自动获得 returned。当您稍后在没有 new 的情况下调用该函数时,this 是您之前创建的 aPerson 对象,因为您使用 callapply 显式设置了上下文.此外,当您不使用 new 时,该函数不会 return 任何东西,它只会分配给 this,这就是 notAPersonnotAPerson2 的原因保持未定义状态。