我是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我不确定这种类型的代码是否可以执行,我是JavaScript的新手。下面是我的执行情况,我希望得到一些关于如何向前推进的反馈。
此外,我想指出,我希望避免创建
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());
发布于 2014-12-12 08:07:29
实际上您要寻找的不是继承,而是建造者模式。如果您确实需要不同的类,则可以将它与工厂模式结合起来。
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();https://stackoverflow.com/questions/27437395
复制相似问题