Example 1 — Default parameters
Constructors accept defaults.
JavaScript
class C { constructor(n = 0){ this.n = n; } }
console.log(new C().n); How It Works
- Missing arg uses 0.
The constructor method runs once when you new a class. Use it to set up this. A class may have only one constructor.
class Counter {
constructor(start) {
this.value = start;
}
}
console.log(new Counter(5).value); Constructors accept defaults.
class C { constructor(n = 0){ this.n = n; } }
console.log(new C().n); Rare: constructor can return another object.
class C { constructor(){ return { ok: true }; } }
console.log(new C().ok); Call before using this.
class A { constructor(){ this.a = 1; } }
class B extends A { constructor(){ super(); this.b = 2; } }
console.log(new B().a, new B().b); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful