本文介绍了Object.assign构造函数中的getter和setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过 Object.assign
定义构造函数中的getter和setter:
I try to define getter and setter in constructor via Object.assign
:
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?
(1) Why getter is called?
(2)为什么不调用getter?
(2) Why getter isn't called?
(3)为什么忽略setter?
(3) Why setter is ignored?
推荐答案
所有三个问题的答案都是一样的:对象。 assign
从源对象读取属性的值,它不会复制getter / setters。
The answer to all three of your questions is the same: Object.assign
reads the value of the property from the source object, it doesn't copy getters/setters.
你可以看到,如果你看一下属性描述符:
You can see that if you look at the property descriptor:
var source = {
get prop() { },
set prop(v) { }
};
console.log("descriptor on source", Object.getOwnPropertyDescriptor(source, "prop"));
var target = Object.assign({}, source);
console.log("descriptor on target", Object.getOwnPropertyDescriptor(target, "prop"));
要在
中
中定义该属性,使用 defineProperty
:
To define that property on this
inside Class
, use defineProperty
:
function Class() {
Object.defineProperty(this, "prop", {
get() { console.log('call get') },
set(v) { console.log('call set') },
});
}
var c = new Class();
console.log(c.prop); // => 'call get', undefined
c.prop = 'change'; // => 'call set'
console.log(c.prop); // => 'call get', undefined
这篇关于Object.assign构造函数中的getter和setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!