[英]Javascript TypeError: … is not a Constructor - How can I make Constructors from Constructors?
我正在嘗試在Javascript中進行對象繼承-是否可以在JavaScript中進行以下操作?
祖父母對象:
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
作為原型返回的結果,而是得到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
“ redsquare
”原型,如下所示:
function square(){}
square.prototype = shape.prototype;
function redbox() {}
redbox.prototype = square.prototype;
我希望這會有所幫助,我已經很清楚了:)
如果我不清楚,那么各種Object.
上都有大量的信息Object.
在MDN上的功能
編輯
繼續下面的最后一條評論,您可以在原型中添加一個super
方法來觸發如下結構:
redbox.prototype.super = square.prototype.super = function super() {
return shape.call(this);
};
這樣,您應該能夠調用square.super()
來運行shape
構造,並且可以對redbox
進行相同的操作。
您還可以包括shape.call(this);
在square
和redbox
函數定義中的代碼可以做到這一點,雖然它看起來更整潔,但是redbox
地說,這是您的選擇,個人喜好使我更喜歡原型。
平方不是函數
您不能從變量實例化,但是,您可以從函數實例化。
另一件事, 形狀不是GrandParentObject,它是您上下文中的構造函數 (= OOP術語中的Class)。
使用此功能:
function inherits(base, extension)
{
for ( var property in base )
{
extension[property] = base[property];
}
}
形狀等級:
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'
return this ;
};
祖父母對象:
var shape1=new shape();
父對象
var square=new shape();
inherits(shape1,square)
square.sides=4;
子對象
var redbox=new shape();
inherits(square,redbox)
redbox.fill='#f00';
更新:
我注意到您在Shape Class( //some methods
)中的注釋。 但是,如果您談論OO,向形狀類添加方法,則將如下所示(使用原型):
shape.prototype.Perimeter=function(){
return this.opts.w * this.opts.h ;
}
然后您可以將其應用到對象shape1中
shape1.Perimeter(); // 10*10=100
這是一個簡單的JavaScript繼承示例:
// Parent class
function Shape (sides) {
this.sides = sides;
this.fill='#fff';
}
// Child class
function Square (fill) {
// run the Parent class' constructor
Shape.call(this, 4);
this.fill = fill;
}
// Instantiate Child class
var redbox = new Square('#f00');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.