Last active
August 29, 2015 14:21
-
-
Save jsteenkamp/32fc7bc191d9162b92bc to your computer and use it in GitHub Desktop.
JavaScript new vs Object.create( ... )
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
*** 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