JavaScript Object.create
Object.create builds a new object with a chosen prototype. The new object starts empty and borrows its methods from that prototype.
Build an object with a chosen prototype
The dog starts with no own properties. Its speak method comes from the animal object, and the check shows the link.
const animal = {
speak: function () {
console.log("Some sound");
}
};
const dog = Object.create(animal);
dog.speak();
console.log(Object.getPrototypeOf(dog) === animal);The new object starts empty
The keys list is empty because the new object holds nothing of its own. The kind value still reads through the chain.
const proto = { kind: "pet" };
const pet = Object.create(proto);
console.log(JSON.stringify(Object.keys(pet)));
console.log(pet.kind);Own data with shared methods
The name is written on the car itself. The start method comes from the prototype and reads that name through this.
const vehicle = {
start: function () {
console.log(this.name + " starts");
}
};
const car = Object.create(vehicle);
car.name = "Civic";
car.start();Example
const shape = {
describe: function () {
console.log("A " + this.sides + "-sided shape");
}
};
const triangle = Object.create(shape);
triangle.sides = 3;
triangle.describe();
console.log(Object.getPrototypeOf(triangle) === shape);Key points
- Object.create: a command that makes an object with a prototype picked by the caller
- The new object holds no own properties at first.
- A property written on the new object stays its own.
- A method found on the prototype still runs with the new object as this.
- Use Object.create to share methods without writing a class.
In this example, Object.create makes a triangle with shape as its prototype. The sides value is written on the triangle itself. The describe method comes from the prototype and reads that own value.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does Object.create(proto) return?