Example 1 — Classes use prototypes
Methods live on Class.prototype.
JavaScript
class A { hi(){ return 1; } }
console.log(new A().hi === A.prototype.hi);How It Works
- Same function shared on the prototype.
Every object has an internal link to another object called its prototype. When you read a property, JavaScript looks on the object, then on its prototype, and so on—the prototype chain—until it finds the property or reaches null.
const animal = { eats: true };
const dog = Object.create(animal);
dog.barks = true;
console.log(dog.barks);
console.log(dog.eats);Methods live on Class.prototype.
class A { hi(){ return 1; } }
console.log(new A().hi === A.prototype.hi);No prototype—pure dictionary.
const d = Object.create(null);
console.log(Object.getPrototypeOf(d));Inspect the link.
console.log(Object.getPrototypeOf([]) === Array.prototype);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