Skip to content

Instantly share code, notes, and snippets.

@davidaurelio
Created February 22, 2011 14:48
  • Star 22 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save davidaurelio/838778 to your computer and use it in GitHub Desktop.
Constructor-less inheritance for ECMAScript 5
var BaseObject = {
create: function create() {
var instance = Object.create(this);
instance._construct.apply(instance, arguments);
return instance;
},
extend: function extend(properties, propertyDescriptors) {
propertyDescriptors = propertyDescriptors || {};
if(properties){
var simpleProperties = Object.getOwnPropertyNames(properties);
for (var i = 0, len = simpleProperties.length; i < len; i += 1) {
var propertyName = simpleProperties[i];
if(propertyDescriptors.hasOwnProperty(propertyName)) {
continue;
}
propertyDescriptors[propertyName] =
Object.getOwnPropertyDescriptor(properties, propertyName);
}
}
return Object.create(this, propertyDescriptors);
},
_construct: function _construct() {},
_super: function _super(definedOn, methodName, args) {
if (typeof methodName !== "string") {
args = methodName;
methodName = "_construct";
}
return Object.getPrototypeOf(definedOn)[methodName].apply(this, args);
}
};
@allenhwkim
Copy link

First, thanks for sharing a nice code.
A question, Is there a reason to write extend: function extend(){} instead of extend: function(){}?

@JanPokorny
Copy link

@bighostkim: It's good for debugging purposes, a stacktrace will show actual function name.

@fernandojunior
Copy link

Hey, I did a code based on yours!
It implements the Class Method concept.
See that https://gist.github.com/fernandojunior/a59c32e6cb8c0736524b
Ty

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