3 ms·
To expand on masklinn's point, Javascript's prototypes are actually very simple. It's just people overcomplicated it so as to do things it wasn't designed for (
by ChrisSD 7y ago
To expand on masklinn's point, Javascript's prototypes are actually very simple. It's just people overcomplicated it so as to do things it wasn't designed for (e.g. emulate Java classes).
These points covers most of what a prototype is:
1. A prototype is simply another object (or null).
2. Every object can have one (and only one) prototype.
3. When looking up a property that doesn't exist on the object, the object will delegate to its prototype.
4. When calling a function on an object, the `this` keyword will be bound to that object, even if the function is defined in the object's prototype.
A simple example to explain what I mean:
// Provide a default implementation of a kitten
const kitten = {
name: "unnamed :(",
greet() {
// Note that `this` will be bound to
// the object that invoked the method
console.log(`Meow! I'm ${this.name}.`);
}
}
// Create a named kitten.
// `Object.create` creates a new object and sets
// its prototype.
const grabbity = Object.create(kitten);
grabbity.name = "Grabbity";
// Call `greet` on the kittens.
kitten.greet(); // outputs "Meow! I'm unnamed :(."
grabbity.greet(); // outputs "Meow! I'm Grabbity."
The only other thing to mention is something you can probably infer: Every prototype is an object therefore a prototype can have its own prototype (and so on). In this way prototypes can be chained.