Skip to content

Instantly share code, notes, and snippets.

@andrewdavey
Created July 3, 2012 14:15
Show Gist options
  • Save andrewdavey/3039979 to your computer and use it in GitHub Desktop.
Save andrewdavey/3039979 to your computer and use it in GitHub Desktop.
Simple object inheritance in JavaScript
(function () {
"use strict";
var copyOwnProperties = function (from, to) {
for (var propertyName in from) {
if (from.hasOwnProperty(propertyName)) {
to[propertyName] = from[propertyName];
}
}
};
var inherit = function (additionalProperties) {
var subclass = Object.create(this);
subclass.create = function () {
// When calling `MyClass.create()` directly, `this` will be `MyClass` as expected.
// When passing `MyClass.create` to another function we lose the intended `this` (it's probably set to `window` or null)
// so explicitly use the `subclass` in that case.
var prototype = (this && this !== window) ? this : subclass;
var instance = Object.create(prototype);
// The instance may have an `initialize` method.
if (typeof instance.initialize === "function") {
instance.initialize.apply(instance, arguments);
}
return instance;
};
copyOwnProperties(additionalProperties, subclass);
return subclass;
};
Object.inherit = inherit;
} ());
var User = Object.inherit({
initialize: function(name) {
this.name = name;
},
sayHello: function() {
console.log("Hello, " + this.name);
}
});
var john = User.create("John");
john.sayHello();
// Can inherit from prototype objects
var SuperUser = User.inherit({
sayHello: function() {
console.log("Hello super, " + this.name);
}
});
// Can pass `create` to other functions and it works as expected
var users = [ "Andrew", "Bob", "Chris" ].map(SuperUser.create);
// users === [ SuperUser.create("Andrew"), SuperUser.create("Bob"), SuperUser.create("Chris") ];
users.forEach(function(user) {
user.sayHello();
});
@bennage
Copy link

bennage commented Jul 3, 2012

This "works":

(john instanceof User.constructor) === true

@andrewdavey
Copy link
Author

Yes, you can't use new or instanceof.

You can use User.isPrototypeOf(john) though.

@andrewdavey
Copy link
Author

It makes sense really, because one "object" cannot be an instance of another "object". I suppose instanceof is really asking wasConstructedBy.

@Flixbox
Copy link

Flixbox commented Apr 12, 2018

I was very confused when I saw this code in the "Programming in HTML5 with JavaScript and CSS3" Microsoft course. Your example really cleared it up for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment