I couldn't find anything matching my exact question so sorry if this is a duplicate.
Given the code:
var Foo = function () {
};
Foo.prototype.log = function (message) {
console.log(message);
};
var Bar = function () {
};
Bar.prototype = Object.create(Foo.prototype);
I can inherit the log(message)
function of Foo
within Bar
and call the following code without issue.
var bar = new Bar();
bar.log("this works");
If I then move the assignment of the prototype to the constructor like follows:
var Foo = function () {
};
Foo.prototype.log = function (message) {
console.log(message);
};
var Bar = function () {
Bar.prototype = Object.create(Foo.prototype);
};
The call to log(message)
will fail
TypeError: bar.log is not a function
Now I'm probably missing something obvious but why is this the case? How would I lazily inherit properties?
The use case I am imagining is inheriting objects from an asynchronously loaded JavaScript file, something like a google.maps.OverlayView
whilst being able to already have the inherited object present in the page.