2009-10-10 2 views
0

저는 지붕, 차고 및 주택에 대한 세 가지 클래스로 JavaScript를 작성하고 있습니다. 하우스 클래스는 생성자 인 Roof and Garage에 두 개의 인수를 취합니다. 이 코드를 실행하면 내가 얻을 :인수가 다른 객체 인 JavaScript 객체 생성자와 관련된 문제

('객체를 생성 할 수 없습니다') 새로운 오류가 발생 오브젝트 [이 오류에 브레이크]를 만들 수 없습니다 \ n 방화범에

개체가 명확에도 불구하고 올바른 유형의 내가 뭘 잘못하고 있는거야? 여기 코드는 다음과 같습니다

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

1

가의 typeof, '객체'를 반환하는 함수의 이름이 아닌 것이다. 'constructor'속성 을 사용해야합니다. '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

+1

'constructor'을 사용하지 마십시오. 표준이 아니며 IE에서는 사용할 수 없으며 프로토 타입을 사용하자마자 생각했던대로 작동하지 않습니다. 자바 스크립트에서 객체의 상속을 테스트하는 유일한 표준, 신뢰할 수있는 방법은'instanceof'입니다. – bobince

+0

일시적인 이상! (에헴) – bobince

1

myRoofmyGarageobject 유형입니다.

myRoofRoof의 인스턴스인지 확인하려면 isinstanceof를 사용하십시오.

>>myRoof isinstanceof Roof 
True 
관련 문제