我尝试通过Object.assign
在构造函数中定义getter和setter:
function Class() {
Object.assign(this, {
get prop() { console.log('call get') },
set prop(v) { console.log('call set') },
});
}
var c = new Class(); // (1) => 'call get'
console.log(c.prop); // (2) => undefined
c.prop = 'change';
console.log(c.prop); // (3) => 'change'
问题:
(1) 为什么会调用 getter?
(2) 为什么没有调用 getter?
(3) 为什么 setter 被忽略了?
return Object.assign({ get prop() { console.log('调用get') }, set prop(v) { console.log('调用set') }}, this); }
- wmikObject.assign
的原始对象。 - T.J. Crowder