Example 1 — With class
Prefer class syntax in modern code.
JavaScript
class Cat { constructor(n){ this.n = n; } }
console.log(new Cat("M").n); How It Works
- constructor runs with new.
The new operator creates an object, sets its prototype from the constructor, binds this inside the constructor, and returns the instance (unless the constructor returns another object).
function Point(x, y) {
this.x = x;
this.y = y;
}
const p = new Point(1, 2);
console.log(p.x, p.y); Prefer class syntax in modern code.
class Cat { constructor(n){ this.n = n; } }
console.log(new Cat("M").n); Can pollute this or throw in classes.
class A {}
try { A(); } catch (e) { console.log(e.name); } new Date(), new Map(), etc.
console.log(new Date(0).getTime()); 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