2014-12-12 4 views
0

나는 JavaScript에 익숙하지 않다 나는 어떤 객체 안에 어떤 객체가 중첩되어 있고 그것들을 모두 결합하기 위해 상속을 사용하고있는 운동을 시도하고있다. 간단히 말해, 주요 목표는 코드 줄을 실행 할 수 있습니다 : 코드의 이러한 유형의 실행 가능한 경우동의 상속

Vehicle1 = new Vehicle("Car"); 
Print(Vehicle.Car("Toyota").Toyota("Red").printEverythingInherited()); //should print Car, Toyota, Red 

Vehicle2 = new Vehicle("Car"); 
Print(Vehicle.Car("Honda").Toyota("Blue").printEverythingInherited()); //should print Car, Honda, Blue 

내가 모르는 걸, 나는 faily 자바 스크립트에 새로운 해요. 아래는 나의 구현이며 앞으로 나아갈 방법에 대한 의견을 듣고 싶습니다.

또한, 나는 내가로 만들 필요가

Car = new Toyota("Blue") 

만들지 않도록 할 것을 지적하고 싶습니다 :

Car = Vehicle("Car").Car("Toyota").Toyota("Blue") 

function Vehicle(type) { 
 
    this.Vehicle = type 
 
} 
 

 
Vehicle.prototype.Car = Car 
 

 
function Car(brand) { 
 
    //Vehicle.call(this, "g") 
 
    this.brand = brand 
 
} 
 

 
Car.prototype.Toyota = Toyota 
 
Car.prototype.Honda = Honda 
 

 
function Honda(color) { 
 
    this.color = color 
 

 
    function printEverythingInherited() { 
 
    print(this.Vehicle + this.brand + this.color) should print Car, Honda, Red 
 
    } 
 
} 
 

 
function Toyota(color) { 
 
    this.color = color 
 
    this.getPriviledgedFunctionColor = function() { 
 
    Log.Message("Toyota() " + this.color) 
 
    } 
 
} 
 

 

 
Vehicle = new Vehicle("Car"); 
 
Print(Vehicle.Car("Toyota").Toyota("Red").printEverythingInherited());

+1

왜 혼다에는'.Toyota' 방법이 있습니까? – Bergi

답변

0

당신 실제로 찾고있는 것은 상속이 아니라, builder pattern. 실제로 다른 수업이 필요한 경우 factory pattern과 결합 할 수 있습니다.

function Factory(props, vals) { 
    if (!vals) vals = []; 
    this.create = function() { 
     return vals.reduce(function(instance, val, i) { 
      instance[props[i]] = val; 
      return instance; 
     }, {}); 
    }; 
    props.forEach(function(prop, i) { 
     this[prop] = function(val) { 
      var nvals = vals.slice(); 
      nvals[i] = val; 
      return new Factory(props, nvals); 
     }; 
    }, this); 
} 
var Vehicle = new Factory(["type", "brand", "color"]); 
var Car = Vehicle.type("car"); 

var car1 = Car.brand("toyota").color("red").create(); 
var car2 = Car.brand("honda").color("blue").create(); 
관련 문제