new Binding
new Binding
Section titled “new Binding”Introduction
Section titled “Introduction”When a function is called with the new keyword, JavaScript creates a new object and sets this to that new object. This is called new binding.
How It Works
Section titled “How It Works”Using new with a constructor function:
function Person(name) { // 'this' = newly created object this.name = name; // 'this' = { name: 'Alice' }}
const alice = new Person('Alice');console.log(alice.name); // 'Alice'What new Does Behind the Scenes
Section titled “What new Does Behind the Scenes”- Creates a brand new empty object
{} - Links the object’s prototype to the function’s
prototype - Sets
thisto the new object - Returns
this(unless the function returns a non-primitive)
function Person(name) { // Step 1 & 2: JS creates {} and links prototype // Step 3: this = {} this.name = name; // this = { name: 'Alice' } // Step 4: return this (implicit)}
// Conceptual equivalent:function newPerson(name) { const obj = {}; Object.setPrototypeOf(obj, Person.prototype); const result = Person.call(obj, name); return result || obj;}Constructor Functions vs Regular Functions
Section titled “Constructor Functions vs Regular Functions”// With new — this = new objectconst alice = new Person('Alice');console.log(alice instanceof Person); // true
// Without new — this = global (default binding!)const bob = Person('Bob');console.log(bob); // undefined (no return)console.log(window.name); // 'Bob' — accidentally set global!Priority
Section titled “Priority”new binding has the highest priority — it overrides explicit binding:
function show() { console.log(this);}
const obj = { name: 'obj' };const bound = show.bind(obj);
new bound(); // this = new object, NOT obj// new binding wins over explicit binding!ES6 Classes
Section titled “ES6 Classes”The new binding is how ES6 classes work:
class User { constructor(name) { // this = new object (created by new) this.name = name; }}
const user = new User('Alice');console.log(user.name); // 'Alice'Best Practices
Section titled “Best Practices”- Always use
newwith constructor functions and classes - Name constructor functions with PascalCase as convention
- Use ES6
classsyntax for cleaner constructors - Ensure constructors always create valid objects
Summary
Section titled “Summary”newcreates a new object and bindsthisto it- Highest priority binding rule
- Functions called with
neware constructors - ES6 classes automatically use
newbinding - Without
new→thisfalls back to default binding