Sometimes its best to keep things quick.
Object.create(Person.prototype)
is pretty simple, but what if we want an inheriting object to overwrite some properties as well as methods? By creating a new object from another’s prototype
, you are only inheriting methods, unless you just don’t care and put all your data in an object’s prototype
.
Of course there are more complex methods of achieving inheritance in javascript, but a lot of those require the use of an api that abstracts from bare bones javascript. Bare bones is good.
So lets keep things simple, quick, and a little dirty. Use $.extend
directly onto the created instance to create an inheritance chain. If jQuery is not your cup of tea, _.extend
, or any generic object extending function will work.
function Person(options) {
$.extend(this, Person.defaults, options);
}
Person.defaults = {
name: '',
age: 0
};
Person.prototype.makeImmortal = function () {
this.age = Infinity;
};
function Guy(options) {
$.extend(this, new Person(options), Guy.defaults, options);
}
Guy.defaults = {
gender: 'male'
};
Guy.prototype.sayName = function () {
return this.name;
};
/*
var person = new Person();
> Person {name: "", age: 0, makeImmortal: function}
var guy = new Guy();
> Guy {name: "", age: 0, makeImmortal: function, gender: "male", sayName: function}
*/
Is new Guy() instanceof Person === true
? Of course not. Did I say it was quick and dirty? Yes.