我目前正在通过一本书学习 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
。
但是我不明白,为什么变量 notAPerson
和 notAPerson2
是未定义的?
如果有人能向我解释一下就太好了。
最佳答案
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
,这就是为什么 notAPerson
和notAPerson2
保持未定义状态。
关于JavaScript call() 和 apply() 方法及变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55052178/