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

标签 javascript call apply 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 是一个全新的对象,它会自动返回。当您稍后在没有 new 的情况下调用该函数时,this 是您之前创建的 aPerson 对象,因为您使用 显式设置了上下文>调用应用。此外,当您不使用 new 时,该函数不会返回任何内容,它只会分配给 this,这就是为什么 notAPersonnotAPerson2 保持未定义状态。

关于JavaScript call() 和 apply() 方法及变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55052178/

相关文章:

javascript - 向下滚动页面时如何使 Logo 出现在固定菜单中

javascript - 处理 JWT 过期和 JWT 有效负载更新

javascript - 来自 Firestore 中子集合的请求的问题

mysql - 如何在 MySQL 中调用过程?

r - 为什么 `as.factor` 在通过 R 中的 `apply` 函数应用时不起作用?

r - 将函数应用于 R 中 data.frame 中的组

javascript - 如何在鼠标悬停时向菜单项添加和删除类

ios - 从另一个 void 获取变量值

C# 在函数调用中使用类的返回值

python - 在返回几列的应用上使用 Dask(DataFrame 等)