-
-
Save samuelgoldenbaum/3039999 to your computer and use it in GitHub Desktop.
Simple object inheritance in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
} ()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment