首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态遗传

动态遗传
EN

Stack Overflow用户
提问于 2014-12-12 05:28:24
回答 1查看 39关注 0票数 0

我是JavaScript的新手,我正在尝试一个练习,在这个练习中,我在某个对象中嵌套了一些对象,并且我使用继承将它们组合在一起。简单地说,主要目标是能够执行这一行代码:

代码语言: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的新手。下面是我的执行情况,我希望得到一些关于如何向前推进的反馈。

此外,我想指出,我希望避免创建

代码语言:javascript
复制
Car = new Toyota("Blue") 

我需要把它创建为:

代码语言:javascript
复制
Car = Vehicle("Car").Car("Toyota").Toyota("Blue")

代码语言:javascript
复制
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());

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-12 08:07:29

实际上您要寻找的不是继承,而是建造者模式。如果您确实需要不同的类,则可以将它与工厂模式结合起来。

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27437395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档