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