2009-10-10 102 views
0

我正在寫一些帶有三個類的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()); 

回答

1

typeof運算符將返回"object"你的對象,而不是他們的名字。見the typeof Operator documentation

function House(roof, garage) { 
    alert(typeof roof); // "object" 
    ... 

你可能想instanceof

function House(roof, garage) { 
    if (!(roof instanceof Roof) || !(garage instanceof Garage)) { 
    ... 
+0

你說得對!那麼如何確保正確的對象被傳入構造函數呢?當我期待屋頂時,我不希望有人通過Foo對象...... – Ralph 2009-10-10 23:09:34

1

正如裏奇指出的typeof會返回 '對象',該功能不是名稱。 您應該使用「構造函數」屬性 。使用'instanceof'操作符。

此外,我已經使用了兩個'if語句'(而不是像你一樣)根據特定的錯誤拋出不同的錯誤消息。這可能意味着更多的代碼,但是當代碼中斷時,您確切知道出了什麼問題。

Working demo →

代碼:

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 (roof instanceof Roof) 
    { 
     throw new Error('Argument roof is not of type Roof'); 
    } 

    if(garage instanceof Garage) 
    { 
      throw new Error('Argument garage must be of type Garage.'); 
    } 

    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()); 
+0

Bobice,你是對的,最好使用instanceof。更正了答案。我不應該急於回答一個問題! :) – SolutionYogi 2009-10-10 23:17:07

+1

不要使用'constructor'。這不是標準的,在IE中不可用,並且只要你開始使用原型就不會做你的想法。在JavaScript中測試對象繼承的唯一標準可靠方法是'instanceof'。 – bobince 2009-10-10 23:18:35

+0

哎呀,時態異常! (ahem) – bobince 2009-10-10 23:19:10

1

myRoofmyGarageobject類型。

如果要檢查myRoof是否爲Roof的實例,請使用isinstanceof。

>>myRoof isinstanceof Roof 
True