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