Skip to content

Instantly share code, notes, and snippets.

@Huxpro
Last active September 22, 2020 09:38
Show Gist options
  • Save Huxpro/92bde9abf1b04101cd8e1cda0828a534 to your computer and use it in GitHub Desktop.
Save Huxpro/92bde9abf1b04101cd8e1cda0828a534 to your computer and use it in GitHub Desktop.
/**
class Super {
x = "super"
}
*/
class Super {
constructor() {
this.x = "super"
}
};
/**
class Sub extends Super {
get x() { return 'sub' }
}
*/
class Sub extends Super {} // constructor() -> super() 里会调用下面的 setter
Object.defineProperty(Sub.prototype, 'x', {
get() { return 'sub' },
set() { console.log('setter') }, // 没有 setter 报错
})
new Sub().x
// setter
// "sub"
/**
class Super {
x = "super"
}
*/
class Super {
constructor() {
Object.defineProperty(this, 'x', {
value: 'super', // 或者 getter
configurable: true // 需要这个
});
}
};
/**
class Sub extends Super {
get x() { return 'sub' }
}
*/
class Sub extends Super {};
Object.defineProperty(Sub.prototype, 'x', {
get() { return 'sub' },
})
new Sub().x; // super
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment