Skip to content

Instantly share code, notes, and snippets.

@jsteenkamp
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsteenkamp/32fc7bc191d9162b92bc to your computer and use it in GitHub Desktop.
Save jsteenkamp/32fc7bc191d9162b92bc to your computer and use it in GitHub Desktop.
JavaScript new vs Object.create( ... )
*** see http://www.quora.com/What-are-some-advanced-JavaScript-techniques-that-you-dont-see-often-but-should ***
*** Don't do this ***
function MyClass() {}
MyClass.prototype.method1 = function () { ... };
MyClass.prototype.method2 = function () { ... };
// ...
MyClass.prototype.methodN = function () { ... };
// ...
}();
var instance = new MyClass();
*** Do this ***
var myProto, makeInstance, instance;
myProto = {
method1 : function () { ... };
method2 : function () { ... };
};
makeInstance = function () { return Object.create( myProto ); };
instance = makeInstance();
*** or this ***
function BaseClass([arg1, arg2, ...]){
//do some initialization with args
}
BaseClass.prototype = {
constructor: BaseClass,
method1: function(){ ... },
method2: fuction(){ ... },
...
methodN: function(){ ... }
};
// Now create the object ("instance")
var myObject = new BaseClass([arg1, arg2, ...]);
*** another option ***
// Note that the MyClass function definition is automatically hoisted.
var _proto = MyClass.prototype;
function MyClass() {}
_proto.method1 = function () {};
_proto.method2 = function () {};
_proto.methodN = function () {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment