use*_*783 0 javascript inheritance prototype class ecmascript-6
这个答案展示了一个简单的 ES6 类如何:
class A {
constructor() {
this.foo = 42;
}
bar() {
console.log(this.foo);
}
}
Run Code Online (Sandbox Code Playgroud)
等价于以下 ES5 代码:
function A() {
this.foo = 42;
}
A.prototype.bar = function() {
console.log(this.foo);
}
Run Code Online (Sandbox Code Playgroud)
是否同样可以将 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);
}
}
Run Code Online (Sandbox Code Playgroud)
之前的实现方式(忽略属性可枚举性和从 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);
};
Run Code Online (Sandbox Code Playgroud)
也可以使用修改现有原型的事实上的工具来继承构造函数(“静态”)的属性: B.__proto__ = A