I know this type of question has been asked and answered a million times, but I still don't understand this.
Everything in JavaScript is an object. There exists a prototype chain that the JavaScript runtime searches for methods and properties. These two things are clear. I also (think I) understand what the new statement does. Maybe the problem is that I don't understand what Object.create
does. I have been using the following JavaScript design pattern:
SuperClass = function(){
this.superprop = 'some super property';
};
SubClass = function(){
this.subprop = 'some (not so) super property';
};
SuperClass.prototype.someSuperMethod = function(){console.log("I'm super.")};
SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;
var instance = new SubClass();
instance.someSuperMethod(); // Great! That's super!
But, I have know clue why I can't write:
SubClass = Object.create(SuperClass);
SubClass = SuperClass;
SubClass = new SuperClass;
SubClass.prototype = SuperClass.prototype;
SubClass = new SuperClass();
SubClass.prototype = SuperClass;
(or any of the combinations above). In short, I guess I don't know what the .prototype property of a function is or why I need to Object.create this prototype if I want SubClass
to inherit everything from SupClass
.
I also don't understand what SuperClass.prototype.constructor
means. How is this object different than SuperClass
?
I also don't understand why I need to write new SubClass()
and not new Subclass
. What's the difference?