In JavaScript what is the difference between these two examples:
Prerequisite:
function SomeBaseClass(){
}
SomeBaseClass.prototype = {
doThis : function(){
},
doThat : function(){
}
}
Inheritance example A using Object.create:
function MyClass(){
}
MyClass.prototype = Object.create(SomeBaseClass.prototype);
Inheritance example B using the new keyword
function MyClass(){
}
MyClass.prototype = new SomeBaseClass();
Both examples seem to do the same thing. When would you chose one over the other?
An additional question: Consider code in below link (line 15), where a reference to the the function's own constructor is stored in the prototype. Why is this useful?
https://github.com/mrdoob/three.js/blob/master/src/loaders/ImageLoader.js
Excerpt (if you don't want to open the link):
THREE.ImageLoader.prototype = {
constructor: THREE.ImageLoader
}
In your question you have mentioned that
Both examples seem to do the same thing, It's not true at all, becauseYour first example
In this example, you are just inheriting
SomeBaseClass' prototypebut what if you have a property in yourSomeBaseClasslikeand if you use it like
The
objobject won't havepublicPropertyproperty like in this example.Your second example
It's executing the
constructorfunction, making an instance ofSomeBaseClassand inheriting the wholeSomeBaseClassobject. So, if you useIn this case its
publicPropertyproperty is also available to theobjobject like in this example.Since the
Object.createis not available in some old browsers, in that case you can useAbove code just adds
Object.createfunction if it's not available so you can useObject.createfunction and I think the code above describes whatObject.createactually does. Hope it'll help in some way.