JavaScript does not use inheritance, it uses delegation from prototype to object.
prototype inheritance is still inheritance, and if there is any delegation, it's the object that delegates missing ownProperty lookups to the prototype...
the OP's change is not visible because he need to manipulate a style object, not a pure js object...
The value of "this" inside a function can by anything, depending on how the function was invoked. When the "move" function is invoked as an onkeyup event handler, then "this" will be the window object instead of the child object that you expected. Here's how we can fix that.
Code:
function Child(x, y) {
this.x = x;
this.y = y;
this.move = function() {
this.x++;
this.y*=2;
this.uber.printf();
};
}
inherit(Child, Parent);
child = new Child(0, 0);
window.onkeyup = function (e) {
// Invoke the "move" function using "child" as the "this" value.
child.move();
e.preventDefault();
};
Next, in the constructors, you create methods by assigning them directly to the new object. This causes problems, because your inheritance goes from prototype to prototype, but you didn't put anything inside the parent or child's prototype. Let's do that now.
Code:
function Parent(x, y) {
// The x and y values are specific to each object,
// so those are assigned in the constructor.
this.x = x;
this.y = y;
}
// printf is shared across all instances,
// so it's assigned in the prototype.
Parent.prototype.printf = function() {
console.log("(" + this.x + ", " + this.y + ")");
};
function Child(x, y) {
this.x = x;
this.y = y;
}
inherit(Child, Parent);
Child.prototype.move = function() {
this.x++;
this.y*=2;
// No need for "uber" here.
// Child.prototype inherits "printf" from Parent.prototype.
// this.uber.printf();
this.printf();
};
But we can still make this slightly better. Notice that you're repeating the same code in the child constructor as you had in the parent constructor. You can eliminate that repetition by invoking the parent constructor, using the current child object as the "this" value for the Parent function.
Bookmarks