Example 1 — Many instances
Each object has its own data.
JavaScript
class C { constructor(n){ this.n = n; } }
console.log(new C(1).n, new C(2).n); How It Works
- Separate instances.
A class is syntax for constructor functions plus prototype methods. You create instances with new. Methods listed in the class body go on the prototype.
class Person {
constructor(name) { this.name = name; }
hello() { return "Hi " + this.name; }
}
console.log(new Person("Ada").hello()); Each object has its own data.
class C { constructor(n){ this.n = n; } }
console.log(new C(1).n, new C(2).n); Classes are functions.
class A {}
console.log(typeof A); Calling without new throws.
class A {}
try { A(); } catch (e) { console.log(e.name); } 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