因此,我有一些课程,我想扩展。除了这些类有getter之外,每当我想通过析构合并/扩展它们的属性时,它都会调用getter函数(调用getter函数)。
是否存在将对象与getter合并而不调用getter的问题?
注意:
的实际问题,我有涉及柏树和链子。我有深层次嵌套的getter(在其中我希望扩展类来扩展它们),它会产生不必要的副作用,就像一个额外的链会导致不想要的行为。
如果运行下面的示例,您将看到多个console.logs正在被调用(这意味着
class Test {
get obj () {
return {
get test () {
const _this = this;
return {
get first () {
const out = _this.wrapper + 'first';
console.log( out );
return out;
}
};
},
get wrapper () {
const out = 'wrapper';
console.log( out );
return out;
}
};
}
}
class Test1 extends Test {
get obj () {
const parent = super.obj;
return {
...parent,
get test() {
console.log( parent );
return {
...parent.test,
get second () {
return super.wrapper + 'hello';
}
};
}
}
}
}
const t = new Test();
const t1 = new Test1();
console.log( t1.obj.test.second );
发布于 2021-05-06 04:02:36
您可以使用Object.getOwnPropertyDescriptors获得对对象描述符(包括getter)的引用,而无需调用它们。使用Object.defineProperties将其放入一个新对象中。
若要添加附加的getter,请在克隆对象上使用Object.defineProperty。
const cloneObj = obj => Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj));
class Test {
get obj() {
return {
get name() {
const _this = this
return {
get first() {
const out = _this.wrapper + 'first'
console.log('get first:', out)
return out
}
}
},
get wrapper() {
const out = 'wrapper'
console.log('get wrapper:', out)
return out
}
}
}
}
class Test1 extends Test {
get obj() {
const parent = super.obj
const parentClone = cloneObj(parent);
Object.defineProperty(parentClone, 'name', { get() {
console.log('child name getter:', parent)
const parentNameClone = cloneObj(parent.name);
Object.defineProperty(parentNameClone, 'second', { get() {
console.log('child second getter:', parent)
return super.wrapper + 'hello';
}});
return parentNameClone;
}});
return parentClone;
}
}
const t1 = new Test1()
console.log('objects fully instantiated.');
console.log(t1.obj.name.second)
结果:

不要启用Stack代码段控制台,因为它会在试图显示对象时调用getter本身,这会让人感到困惑。
https://stackoverflow.com/questions/67411624
复制相似问题