JavaScript 函数特性深度解析
1. 构造函数中 this 的检查与 new.target 元属性
在 JavaScript 中,我们常常需要判断一个函数是否是通过 new 关键字调用的。传统的做法是检查 this 是否是构造函数的实例,示例代码如下:
function Person(name) {
if (this instanceof Person) {
this.name = name;
} else {
throw new Error("You must use new with Person.")
}
}
var person = new Person("Nicholas");
var notAPerson = Person.call(person, "Michael"); // works!
在上述代码中, Person.call(person, "Michael") 调用时, this 被设置为 person ,函数无法区分是通过 new 调用还是通过 call 或 apply 调用。
为了解决这个问题,ES6 引入了 new.target 元属性。当函数的
超级会员免费看
订阅专栏 解锁全文
1048

被折叠的 条评论
为什么被折叠?



