I'm learning myself JavaScript, but I'm confused about the whole prototyping and inheritance in JavaScript.
Example 1:
function MyClass() {
this.my_var = "1";
}
function MyClass2() {
this.my_var2 = "2";
}
MyClass2.prototype = new MyClass();
class2 = new MyClass2();
console.log(class2.my_var);
console.log(class2.my_var2);
This is the easiest one to understand. the prototype of MyClass2 is a MyClass object, so it seems natural that class2 has access to its properties.
Example 2:
I wondered if it was possible to set the prototype in the constructor function itself:
function MyClass() {
this.my_var = "1";
}
function MyClass2() {
this.my_var2 = "2";
this.prototype = new MyClass();
}
class2 = new MyClass2();
console.log(class2.my_var);
console.log(class2.my_var2);
This doesn't seem to work however. my_var appears to be undefined.
Example 3:
Let's try another approach, this time using Object.create():
function MyClass() {
this.my_var = "1";
}
function MyClass2() {
this.my_var2 = "2";
}
MyClass2.prototype = Object.create(MyClass);
class2 = new MyClass2();
console.log(class2.my_var);
console.log(class2.my_var2);
No luck either, my_var appears to be undefined.
Example 4:
This time, I'm using NodeJS "inherits()" function from the "util" module:
util = require("util");
function MyClass() {
this.my_var = "1";
}
function MyClass2() {
this.my_var2 = "2";
}
util.inherits(MyClass2, MyClass);
class2 = new MyClass2();
console.log(class2.my_var);
console.log(class2.my_var2);
I understand why example 1 works, but I don't understand why 2,3 and 4 do not. I hope someone can explain me why that is the case.
this.__proto__ = new MyClass();thisis just a regular object, so.prototypedoes nothing special. 3 doesn't work because you should be usingObject.create(MyClass.prototype)and using.applyto inMyClass2to invokeMyClassonthis.Object.createseems more sensible.__proto__. Do it only for learning.