【问题标题】:Get property of class from an instance of subclass从子类的实例中获取类的属性
【发布时间】:2019-06-28 05:39:27
【问题描述】:

据我所知,构造函数的 __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;
}

【问题讨论】:

  • Object.getPrototypeOf() ?但是为什么需要访问超类呢?如果您正在执行此方法,则可以使用super。我不认为与类的 instance 一起工作的代码应该对其实现做出任何假设。
  • 这与为我的样式获取适当的CSS类以使其生效@FelixKling有关。我更新了 sn-p 以更清楚地说明我的目标。

标签: javascript ecmascript-6 es6-class


【解决方案1】:

你可以使用静态方法和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;
}

【讨论】:

  • 谢谢你,菲利克斯。我的代码中需要这个 __proto__ ?
猜你喜欢
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 2014-02-16
  • 2021-11-07
相关资源
最近更新 更多