Let's say I have the following simple OOP-like implementation:
Implementation 1:
function Base() {
this.text = "lol";
}
Base.prototype.hello = function() {
console.log("Hello from base");
}
function Child() {
}
Child.prototype = new Base(); // All objects created from Child function now have reference to this Base object in their __proto__ property.
Child.prototype.hello = function() { // Changes the hello implementation in the prototype object
console.log("Hello from child");
}
var child1 = new Child();
child1.hello(); // "Hello from child"
This is the implementation I see more often: The methods that are supposed to be inherited (like the hello method) from the Base object to child objects are defined using the prototype property.
However, if I bind the hello method right in to the base object using this keyword I get the same result:
Implementation 2:
function Base() {
this.text = "lol";
this.hello = function() {
console.log("Hello from base");
}
}
function Child() {
}
Child.prototype = new Base(); // All objects created from Child function now have reference to this Base object in their __proto__ property.
Child.prototype.hello = function() { // Changes the hello implementation in the prototype object
console.log("Hello from child");
}
var child1 = new Child();
child1.hello(); // "Hello from child"
What's the difference between these two implementations?