JavaScript: new
The new operator creates an object instance by calling a constructor.
What you will learn
- How
newcalls a constructor and creates an instance - How to create built-in objects and instances of your own class
- How
newdiffers from calling an ordinary function
Built-in objects
const myDate = new Date();
const myRegExp = new RegExp("^web");
console.log(myDate);
console.log(myRegExp.test("web programming"));JavaScript creates a new object and returns it to the variable. The constructor can use its arguments to set the initial state.
Custom classes
class Player {
constructor(name) {
this.name = name;
}
}
const hero = new Player("Yuki");
console.log(hero.name);new Player("Yuki") creates an instance and runs the class constructor. For ordinary boolean values, prefer true or false over new Boolean(), because wrapper objects can be confusing.