跳到主要内容

new.target 是什么意思

new.target 是一个特殊的元属性,在 JavaScript 中用于指示一个函数是否被作为构造函数调用。它可以帮助我们确定当前函数执行的上下文,特别是在类和构造函数中。

主要特点

  1. 构造函数中的使用

    • 当在构造函数内部使用 new.target 时,它会指向调用该构造函数的构造函数。如果该构造函数是直接调用的(即通过 new 关键字),new.target 将是 undefined
    • 这允许我们在构造函数中确认是否以 new 关键字调用了该函数。
  2. 防止错误调用

    • 使用 new.target 可以防止用户错误地调用构造函数而不使用 new,从而避免潜在的错误。
  3. 在类中的使用

    • 在类的构造函数中,可以使用 new.target 来检测类是否被实例化。

示例

以下是一些示例,展示了 new.target 的用法:

// 构造函数示例
function Person(name) {
if (!new.target) {
throw new Error("必须使用 new 关键字调用 Person 构造函数");
}
this.name = name;
}

const john = new Person('John'); // 正确
console.log(john.name); // 输出: John

// const jane = Person('Jane'); // 报错: 必须使用 new 关键字调用 Person 构造函数

// 类示例
class Animal {
constructor(name) {
if (!new.target) {
throw new Error("必须使用 new 关键字调用 Animal 构造函数");
}
this.name = name;
}
}

const dog = new Animal('Dog'); // 正确
console.log(dog.name); // 输出: Dog

// const cat = Animal('Cat'); // 报错: 必须使用 new 关键字调用 Animal 构造函数
function Person(name) {
console.log('new target->', new.target);
console.log('new.target === Person->', new.target === Person);
this.name = name;
}

let p = new Person("Hello")
console.log(p);
// new target -> true
// Person { name: 'Hello' }

let m = Person("ttt");
console.log(m);
// new.target === Person -> false
// undefined

总结

  • new.target 是一个非常有用的特性,可以帮助确保构造函数或类以正确的方式被调用。
  • 它在处理构造函数的上下文时提供了更好的控制,尤其是在防止错误调用时。