JavaScript调用()和apply()方法以及变量赋值
我目前正在使用一本书学习JavaScript。一个例子解释了函数的双重用途JavaScript调用()和apply()方法以及变量赋值,javascript,call,apply,variable-assignment,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
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
调用函数时,它的工作方式如下:
function Person(name) {
var this = {}
if (this instanceof Person) {
this.name = name
} else {
throw new Error("Nutze new")
}
return this
}
因此,当您使用new
调用函数时,这是一个全新的对象,它会自动返回。当您稍后在不使用new
的情况下调用函数时,这是您先前创建的aPerson
对象,因为您正在使用call
和apply
显式设置上下文。另外,当您不使用new
时,函数不会返回任何内容,它只分配给this
,这就是notAPerson
和notAPerson2
保持未定义的原因。因为构造函数不返回值。它只是修改了这个
对象。我想把它标记为一个打字错误,但我不确定我应该这样做。实际上,您会问为什么调用函数时不返回任何东西(){console.log(“这是整个主体”)}
不会产生值。非常感谢。现在我明白了。我很高兴能帮你把事情弄清楚。如果您认为此答案回答了您的问题,请选择“正确”。