Saben JavaScript object duwe hubungan tersembunyi menyang object liyane sing diarani prototype. Saat sampeyan ngakses property, JS nggoleki ing object dhewe, banjur mlaku munggah ing prototype chain nganti nemokne property utawa nggawe null. Iki isih delegation, dudu ngubengi.
const animal = {
speak() { return `${this.name} makes a sound`; },
};
const dog = Object.create(animal); // dog's prototype IS animal
dog.name = "Rex";
dog.speak(); // "Rex makes a sound" — found on the prototype
Object.getPrototypeOf(dog) === animal; // true
dog.hasOwnProperty("speak"); // false — it's inherited, not own
dog.hasOwnProperty("name"); // true
Piye classes nggunakne
class adalah syntax sugar menyang prototypes. Methods manggon sesowan ing prototype, dibagi dening kabeh instances (ora dicopya per object):
class Dog {
constructor(name) { this.name = name; }
speak() { return `${this.name} barks`; } // on Dog.prototype
}
const d = new Dog("Rex");
Object.getPrototypeOf(d) === Dog.prototype; // true
Dadi d.speak ora nyimpen ing d — iku ditemokne dening mlaku munggah menyang Dog.prototype. Kuwi sebab kabeh dog ibagi siji function speak (hemat memori).
Apa gunane
Pangertosan chain njelasne: kenapa instances ibagi methods, kenapa owah-owahan prototype nagaruhi kabeh linked objects, piye instanceof bisa berfungsi (iku ngecheck chain), lan biaya ring lookup chains sing dawa.
Iku fondasi ing jero class, built-ins (Array.prototype.map), lan inheritance.
