[英]Can ES6 class inheritance be translated into equivalent ES5 code?
这个答案展示了一个简单的 ES6 类:
class A {
constructor() {
this.foo = 42;
}
bar() {
console.log(this.foo);
}
}
等效于以下 ES5 代码:
function A() {
this.foo = 42;
}
A.prototype.bar = function() {
console.log(this.foo);
}
是否可以将 ES6 类继承转换为 ES5 代码? ES5 相当于以下派生类是什么?
class B extends A {
constructor() {
super();
this.foo2 = 12;
}
bar() {
console.log(this.foo + this.foo2);
}
baz() {
console.log(this.foo - this.foo2);
}
}
之前的实现方式(忽略属性可枚举性和从 ES5 兼容代码扩展实际 ES6 类的确切行为)的等价物是:
function B() {
A.call(this);
this.foo2 = 12;
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.bar = function () {
console.log(this.foo + this.foo2);
};
B.prototype.baz = function () {
console.log(this.foo - this.foo2);
};
也可以使用修改现有原型的事实上的工具来继承构造函数(“静态”)的属性: B.__proto__ = A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.