
The new Keyword in JavaScript
If you've ever written new Person("Alice") and wondered what's actually happening behind the scenes — this post is for you. what is constructor function? A constructor function is just a regular function, but by convention we capitalize its name to signal it should be called with new. function Person ( name , age ) { this . name = name ; this . age = age ; } Inside it, this refers to the new object being built. That's the key idea. What does new actually do? When you write: const alice = new Person ( " Alice " , 30 ); JavaScript silently does four things for you: Creates a brand-new empty object // internally: const this = {}; 2.Links it to the constructor's prototype // internally: this.__proto__ = Person.prototype; This is how alice can call methods like greet() even though they aren't stored on alice itself. 3.Runs the constructor body with this as that new object this . name = " Alice " ; 4.Returns the object automatically.You don't need a return statement — new handles it Putting
Continue reading on Dev.to
Opens in a new tab


