I was experimenting with Object.create() way of inheritance in Javascript.
While I clearly understand that this is how the inheritance is achieved using Object.create().
//Inheritance with Object.create()
function superClass(){
this.name = "I'm a name in superclass";
this.name2 = "Someone please pickup the phone.";
}
superClass.prototype.useMe = function(){
this.name3 = "I'm name3";
this.name4 = "I'm name4";
}
function subClass() {
superClass.call(this);
}
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
var obj = new subClass();
console.log(obj.constructor);
Output:
function subClass() {
superClass.call(this);
}
The confusion arose when I moved the positioning of these two lines,
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
See below,
//Inheritance with Object.create()
function superClass(){
this.name = "I'm a name in superclass";
this.name2 = "Someone please pickup the phone.";
}
superClass.prototype.useMe = function(){
this.name3 = "I'm name3";
this.name4 = "I'm name4";
}
function subClass() {
superClass.call(this);
}
var obj = new subClass();
subClass.prototype = Object.create(superClass.prototype);
//I've commented the constructor assignment.
//subClass.prototype.constructor = subClass;
console.log(obj.constructor);
Output:
function subClass() {
superClass.call(this);
}
Isn't this suppose to return the constructor function as superClass as I commented the constructor assignment line.
Now, the question is; Is the positioning of subClass.prototype = Object.create(superClass.prototype);
is really important?
Case 1: When I placed it above the object creation line, the assignment of new constructor function was required.
Case 2: When I placed it below the object creation line, I don't think we need the constructor assignment line, as it's clearly referencing the proper constructor function.
Thanks for the help.
Edit: I'm not mixing Object.create with constructor function.
My only confusion was; when I placed the line subClass.prototype = Object.create(superClass);
after the object creation, it should change the subClass.prototype.constructor
to superClass
's constructor. But it didn't it is taking the subClass's constructor. How? Or, am I missing something here.