This is a follow-up to Classes in JavaScript
In my previous post, we learned how you can create classes in JavaScript using
the new
operator and a temporary constructor function. This post will show
how you can use the Object.create() method to setup the prototype without using
new.
Object.create()
was added to
ECMAScript 5.1 spec
in June of 2011 and is supported in all major browsers including IE9+. This
method takes two parameters, the first being the parent object you’re inheriting
from and the second being an optional object that defines values that will be
placed on the newly created object:
function Actor() {
this.x = 0;
this.y = 0;
}
Actor.prototype.move = function(x, y){
this.x = x;
this.y = y;
}
function Player() {
Actor.call(this);
this.health = 100;
}
Player.prototype = Object.create(Actor.prototype, {type: {value: "Human"}});
function Monster() {
Actor.call(this);
this.health = 10;
}
Monster.prototype = Object.create(Actor.prototype, {type: {value: "Unknown"}});
var p = new Player();
var m = new Monster();
p.move(100, 150);
console.log(p); // {x: 100, y: 150, health: 100}
console.log(p.type); // "Human"
By using Object.create we can make objects that inherit properties from a parent object. We can also define new properties that will be We can then define unique properties on the child.
This pattern is called is called prototypal inheritance and is actually just one of a number of ways you can perform class like inheritance in JavaScript. You can read more about other patterns on David Shariffs post JavaScript Inheritance Patterns.