2017-05-26 104 views
0

我的問題標題可能看起來完全混亂,這反映了我現在的心境:P如何使構造函數指向超級函數原型ES5

我再次拜訪的JavaScript繼承世界的基礎。下面的例子應該告訴我是想:

function Vehicle(engType, wheels, color){ 
    this._engType = engType; 
    this._wheels = wheels; 
    this._color = color; 
} 

var VP = Vehicle.prototype; 

VP.setEngType = function(engType){ 
    this._engType = engType; 
} 

VP.setWheels = function(wheels){ 
    this._wheels = wheels; 
} 

VP.setColor = function(color){ 
    this._color = color; 
} 


function Car(cc, gears){ 
    this._cc = cc; 
    this._gears = gears; 
} 


Car.prototype = new Vehicle(); 

車輛超類型有自己的一套屬性和汽車有自己的是子類型的車輛。

一切都很好,直到這裏,但一旦我創造汽車的實例,並要設置其母公司的其他屬性說engType/wheels/color我需要使用Set訪問方法這是一個開銷。在Car(Sub-Type)構造函數中是否有任何方法可以立即使用它。像:

function Car(cc, gears, engType, wheels, color){ 
    this._cc = cc; 
    this._gears = gears; 

    // Setting super type props 
    this.setEngType(engType); 
    this.setWheels(wheels); 
    this.setColor(color); 
} 

回答

1

你可以這樣調用,

function Car(cc, gears, engType, wheels, color){ 
    Vehicle.call(this,engType,wheels,color); 
    this._cc = cc; 
    this._gears = gears;  
} 

Car.prototype = Object.create(Vehicle.prototype); 
Car.prototype.constructor = Car; 

有關詳細信息,請參閱本website

1

你想call的新實例(this)的父類的構造做初始化:

function Car(cc, gears, engType, wheels, color) { 
    Vehicle.call(this, engType, wheels, color); 
    this._cc = cc; 
    this._gears = gears; 
} 

don't use a new call創建原型:

Car.prototype = Object.create(VP);