【发布时间】:2016-02-29 22:15:43
【问题描述】:
假设有一个父类Shape和一个子类Rectangle。我想在子类中重用父类属性的值。
我可以在不重新初始化子类的情况下执行此操作吗(使用调用或应用)?
我希望所有子对象都使用相同的父属性值。
//Parent
function Shape(ctx) {
this.context = ctx;
}
Shape.prototype.getContext = function() { return this.context; };
//Child - rectangle inherits from shape
function Rectangle(x,y,w,h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
//setup inheritance
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.draw = function() {
//want to use inherited context here
return this.context;
}
//create and run
var shape = new Shape("value");
var rectangle = new Rectangle(0,0,100,100);
//returns "value"
console.log( shape.getContext() );
//returns undefined - needing "value"
console.log( rectangle.draw() );
编辑 - 在下面的回复之后,我认为这就是我需要的。由于矩形实例不是从形状实例继承的,因此分配给形状的“值”不会传递给矩形。如何将其分配为 Shape 内部的默认值,然后在 Rectangle 构造函数中调用 Shape 构造函数。这允许我向所有子对象共享相同的上下文值,对吗?
附带问题,setter 不会影响 Shape 子级。所以我正在努力。
//Parent
function Shape() {
this.context = "value";
}
Shape.prototype.getContext = function() { return this.context; };
Shape.prototype.setContext = function(x) { this.context = x; };
//Child - rectangle inherits from shape
function Rectangle(x,y,w,h) {
Shape.call(this);
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
//setup inheritance
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.draw = function() {
//want to use inherited context here
return this.context;
}
//create and run
var rectangle = new Rectangle(0,0,100,100);
//returns "value"
console.log( rectangle.draw() );
编辑 - 感谢回复,我认为下面正在完成我最初尝试做的事情。 Shape 父级以默认上下文值开头。 Shape 构造函数现在还接受一个参数,以防子类在最初调用时想要更改它。然后,每个子类都有一个用于上下文的 getter 和 setter,但除非更改,否则它将始终默认为初始 Parent 值。在深入研究之后,Shape 开始感觉像是一个抽象类或接口,但这与我最初的要求无关。
//Parent
function Shape(ctx) {
this.context = (typeof ctx === "undefined") ? "default" : ctx;
}
Shape.prototype.getContext = function() { return this.context; };
Shape.prototype.setContext = function(x) { this.context = x; };
//Child - rectangle inherits from shape
function Rectangle(x,y,w,h) {
//calls parent constructor
Shape.call(this);
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
//setup inheritance
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
//getter and setter - context defaults to parent value, but can be changed
Rectangle.prototype.getContext = function() { return this.context; };
Rectangle.prototype.setContext = function(x) { this.context = x; };
//other rectangle methods
Rectangle.prototype.draw = function() {
return "doing something with " + this.context;
}
//create and run
var rectangle = new Rectangle(0,0,100,100);
//starts with Parent "default"
console.log( rectangle.getContext() );
//changes and uses different context
rectangle.setContext("different context");
console.log( rectangle.draw() );
【问题讨论】:
-
您的
rectangle实例并非源自该shape实例。
标签: javascript inheritance prototype