Skip to content

Instantly share code, notes, and snippets.

@Huxpro
Last active September 22, 2020 09:27
Show Gist options
  • Save Huxpro/9f722c39a45137e3f7285a981ddb3743 to your computer and use it in GitHub Desktop.
Save Huxpro/9f722c39a45137e3f7285a981ddb3743 to your computer and use it in GitHub Desktop.
Emulate ES Next Class
// 试了两种方式模拟:
class Super {
constructor() {
this.x = "super"
}
};
// 这样的话也是 own property
new Super().hasOwnProperty('x') // true
class Sub extends Super {
constructor() {
super();
Object.defineProperty(this, 'x', {
get() { return 'sub'; }
});
}
}
new Super().x // "super"
// 成功 override
new Sub().x // sub
class Super {
constructor() {
Object.defineProperty(this, 'x', {
value: 'super', // 或者 getter
configurable: true // 需要这个
});
}
};
class Sub extends Super {
constructor() {
super();
Object.defineProperty(this, 'x', {
get() { return 'sub'; }
});
}
}
new Super().x // "super"
// 成功 override
new Sub().x // "sub"
// 如果 Sub 的 get/set methods 是 lower 在 prototype 上
/**
class Sub2 extends Super {
get x() { return 'sub2' }
}
*/
class Sub2 extends Super {}
Object.defineProperty(Sub2.prototype, 'x', {
get() { return 'sub2' }
})
new Sub2().x // "super" <--- ownProperty 优先
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment