从子类的实例获取类的属性

时间:2019-06-28 05:39:27

标签: javascript ecmascript-6 es6-class

据我所知,构造函数的__proto__属性被视为已弃用。是否有更好的方法从子类的已创建实例访问父类的属性?

示例:

在下面的示例中,请求的属性为cls

class Vehicle {
  constructor () {
    var div = document.createElement("div");
    var cls = this.constructor.__proto__.cls + " " + this.constructor.cls;
    div.setAttribute("class", cls);
    document.body.appendChild(div);
  }
}
class Car extends Vehicle {}
class Motorcycle extends Vehicle {}

Vehicle.cls = "vehicle";
Car.cls = "car";
Motorcycle.cls = "motorcycle";

let vehicle = new Vehicle();
let car = new Car();
let bike = new Motorcycle();
.vehicle {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-color: red;
}

.car {
  background-color: green;
}

.motorcycle {
  background-color: blue;
}

1 个答案:

答案 0 :(得分:2)

您可以使用静态方法和super

class Vehicle {
  constructor () {
    var div = document.createElement("div");
    var cls = new.target.getCls();
    div.setAttribute("class", cls);
    document.body.appendChild(div);
  }
  
  static getCls() {
    return 'vehicle';
  }
}
class Car extends Vehicle {
  static getCls() {
    return 'car ' + super.getCls();
  }
}
class Motorcycle extends Vehicle {
  static getCls() {
    return 'motorcycle ' + super.getCls();
  }
}

let vehicle = new Vehicle();
let car = new Car();
let bike = new Motorcycle();
.vehicle {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-color: red;
}

.car {
  background-color: green;
}

.motorcycle {
  background-color: blue;
}

这允许子类确定自己如何构建类列表。

如果您总是想添加基类的CSS类,为什么不直接访问它呢?

class Vehicle {
  constructor () {
    var div = document.createElement("div");
    var cls = Vehicle.cls + " " + new.target.cls;
    div.setAttribute("class", cls);
    document.body.appendChild(div);
  }
}
class Car extends Vehicle {}
class Motorcycle extends Vehicle {}

Vehicle.cls = "vehicle";
Car.cls = "car";
Motorcycle.cls = "motorcycle";

let vehicle = new Vehicle();
let car = new Car();
let bike = new Motorcycle();
.vehicle {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-color: red;
}

.car {
  background-color: green;
}

.motorcycle {
  background-color: blue;
}