M
mmcloughlin
I'm learning about objects and am trying to figure out how basic
inheritance works. I've got into the habit of explicitly setting the
prototype object with an object literal as it seems to make the
creation of a class easier to read/understand.
Anyway it seems to break the inheritance chain in the following code
and I don't know why.
window.onload = function() {
var p = new Parent();
alert(p.property); // works
var c = new Child();
alert(c.property); // doesn't work, alerts "undefined"
}
function Child() {}
Child.prototype = new Parent();
function Parent() {}
Parent.prototype = {property: "Hello from Parent's prototype."};
If you replace the last line with
Parent.prototype.property = "Hello from Parent's prototype.";
then the whole thing works. Does anyone know why this is happening?
inheritance works. I've got into the habit of explicitly setting the
prototype object with an object literal as it seems to make the
creation of a class easier to read/understand.
Anyway it seems to break the inheritance chain in the following code
and I don't know why.
window.onload = function() {
var p = new Parent();
alert(p.property); // works
var c = new Child();
alert(c.property); // doesn't work, alerts "undefined"
}
function Child() {}
Child.prototype = new Parent();
function Parent() {}
Parent.prototype = {property: "Hello from Parent's prototype."};
If you replace the last line with
Parent.prototype.property = "Hello from Parent's prototype.";
then the whole thing works. Does anyone know why this is happening?