我正在尝试在 Javascript 中进行对象继承 - 在 javascript 中可以执行以下操作吗?
祖 parent 对象:
var shape=function(paramOpts){
this.opts={x:0,y:0,h:10,w:10};
$.extend(true,this.opts,paramOpts);
this.sides=0;
this.fill='#fff';
this.outline='#000';
// some methods
};
父对象
var square=new shape();
square.sides=4;
子对象
var redbox=new square();
redbox.fill='#f00';
运行此程序时,我收到错误TypeError: square is not a Constructor
。
如何使 square
成为构造函数?
最佳答案
当您创建square
时,您不会得到Function
作为原型(prototype)返回,而是得到shape
。
您可以通过多种方式个人继承;我喜欢使用 Object.create()
即
function shape(paramOpts){
this.opts={x:0,y:0,h:10,w:10};
$.extend(true,this.opts,paramOpts);
this.sides=0;
this.fill='#fff';
this.outline='#000';
// some methods
};
var square = Object.create(shape);
square.sides = 4;
var redbox = Object.create(square);
redbox.fill = '#f00';
对 Object.create
的支持可以追溯到 IE9,但仅此而已,有很多垫片可以为您执行此操作。
如果您不想使用填充程序,您可以按照经典方式进行操作,形状定义的方法将在 shape
的 prototype
链上定义,即:
shape.prototype.setFill = function shape_fill(colour) {
this.fill = colour;
return this;
};
您对 square
和 redsquare
的以下定义将简单地从 shape
中“获取”原型(prototype),如下所示:
function square(){}
square.prototype = shape.prototype;
function redbox() {}
redbox.prototype = square.prototype;
我希望这有帮助,我已经说得很清楚了:)
如果我没有说清楚的话,MDN 上有大量关于各种 Object.
函数的信息。
编辑
继续我下面的最后一条评论,您可以向原型(prototype)添加一个 super
方法来触发构造,如下所示:
redbox.prototype.super = square.prototype.super = function super() {
return shape.call(this);
};
这样,您应该能够调用 square.super()
来运行 shape
构造,并且您可以对 redbox
执行相同的操作做同样的事情。
您还可以在 square
和 redbox
函数定义中包含 shape.call(this);
代码来执行此操作,可能会更简洁但这是你诚实的选择,个人品味让我更喜欢原型(prototype)。
关于Javascript TypeError : . ..不是构造函数 - 如何从构造函数创建构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23539251/