New is the command that the constructor generates the instance. ES6 introduces the new.target property for the new command. This property is used to determine how the constructor is called.
In the constructor, if a constructor is not called through the new operator, new.target returns undefined.
Usage scenarios
If a constructor does not generate an instance through the new command, an error alert will be reported
This is done in es5:
function Shape(options) { if (this instanceof Shape) { this.options = options } else { // Either create an instance of it manually and return // return new Shape(options) // Or remind throw new Error('Shape Constructor must use new Operator') } }
This can be done in es6:
function Shape(options) { // If (new.target! = = 'undefined') {} must use new.target in constructor, and error will be reported here constructor(options) { if (new.target !== 'undefined') { this.options = options } else { throw new Error('Must use new Operator') } } }
The above code judges whether the returned function is undefined through the new.target property to know whether the constructor is called through the new operator
A constructor can only be used for subclass inheritance, and cannot be new by itself
The property new.target returns the constructor name of the subclass when the subclass inherits the parent class
class Parent { constructor() { console.log(new.target) } } class Child extends Parent { constructor() { super() } } // Child
The Child subclass of the above code inherits the parent class, so the new.target in the parent class constructor is the name of the subclass constructor.
Specifies that constructors can only be used for inheritance
class Zoo { constructor() { if (new.target === Zoo) throw new Error('Zoo Constructors can only be used for subclass inheritance') } } const zoo = new Zoo() // Report errors class Dog extends Zoo { constructor() { super() } } const dog = new Dog() // No mistake
Tip: if new.target is used externally, an error will be reported