父静态方法返回子类对象

时间:2018-02-04 03:42:44

标签: javascript es6-class

class Vehicle {
    constructor (name, type) {
        this.name = name;
        this.type = type;

        console.log(this.constructor.name);
    }
    getName () {
        return this.name;
    }
    getType () {
        return this.type;
    }
    static create(name, type) {
        return new Vehicle(name, type);
    }
}

class Car extends Vehicle {
    constructor (name) {
        super(name, 'car');
    }
    getName () {
        return 'It is a car: ' + super.getName();
    }
}

let car = Car.create('Tesla', 'car');
console.log(car.getName()); // It is a car: Tesla
console.log(car.getType()); // car

上面的代码使用ES6 class关键字来定义Vehicle类和子类Car。如何从Vehicle静态方法返回Car实例。

2 个答案:

答案 0 :(得分:0)

尝试:

let car = new Car('Tesla')

答案 1 :(得分:0)

您可以在静态函数ClassName中传递要使用的create并从中创建实例。

static create(name, type, objClass) {
    return new Function(`return new ${objClass ? objClass : 'Vehicle'}('${name}', '${type}');`)();
}

在您的情况下,Function类接收带有要评估的表达式的String:

new Function(`return new ${objClass}('${name}', '${type}');`)()

查看此代码



class Vehicle {
  constructor(name, type) {
    this.name = name;
    this.type = type;
  }
  getName() {
    return this.name;
  }
  getType() {
    return this.type;
  }
  static create(name, type, objClass) {
    return new Function(`return new ${objClass ? objClass : 'Vehicle'}('${name}', '${type}');`)();
  }
}

class Car extends Vehicle {
  constructor(name) {
    super(name, 'car');
  }

  getName() {
    return 'It is a car: ' + super.getName();
  }
}

let car = Car.create('Tesla', 'car', 'Car');
console.log(car.getName()); // It is a car: Tesla
console.log(car.getType()); // car

let superCar = Vehicle.create('Tesla', 'car');
console.log(superCar.getName()); // Tesla
console.log(superCar.getType()); // car

.as-console-wrapper {
  max-height: 100% !important
}




请参阅?现在正在打印正确的输出。

资源