我正在寫一些帶有三個類的JavaScript,一個用於屋頂,一個用於車庫,另一個用於房屋。房屋類的構造函數有兩個參數,一個Roof和一個Garage。當我運行這段代碼,我得到:JavaScript對象構造函數的問題,其中的參數是其他對象
不能構造對象[打破這個錯誤]拋出新的錯誤(「不能構造對象」); \ n
在Firebug即使對象是明確正確的類型。任何想法我做錯了什麼?下面的代碼:
function Roof(type, material) {
this.getType = function() { return type; }
this.getMaterial = function() { return material; }
}
function Garage(numberOfCars) {
this.getNumberOfCars = function() { return numberOfCars; }
}
function House(roof, garage) {
if (typeof roof !== 'Roof' || typeof garage !== 'Garage') {
throw new Error('can not construct object');
}
this.getRoof = function() { return roof; }
this.getGarage = function() { return garage; }
}
myRoof = new Roof("cross gabled", "wood");
myGarage = new Garage(3);
myHouse = new House(myRoof, myGarage);
alert(myHouse.getRoof().getType());
你說得對!那麼如何確保正確的對象被傳入構造函數呢?當我期待屋頂時,我不希望有人通過Foo對象...... – Ralph 2009-10-10 23:09:34