Appearance
前言
上班中突然对class 继承后元数据也能继承感到特别疑惑,详细再记录下class 继承的过程。本文都已class转换为es5为基准
class -> es5
直接上代码
ts
class Parent {
a: number
constructor() {
this.a = 1
}
b = 1
methodA() {
console.log('method A')
}
}
class Child extends Parent {
childMethod() {}
}转换后的大致代码
js
function Parent {
this.b = 1
this.a = 1
}
Parent.prototype.methodA = function() {
console.log('method Parent')
}
function _extends(Parent, Child) {
// 继承静态方法属性
Object.setPrototypeOf(Child, Parent)
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
}
function Child {
Parent.call(this)
}
_extends(Parent, Child)
Child.prototype.childMethod = function() {}分析
从上面可以看出,如果在Parent 使用class decorator。 可以检查构造函数的原型链来查询所有的元信息
