我有一个类,它有一个私有(private)数组和一个返回所述数组的过滤版本的 getter。我希望能够简单地调用已过滤数组的推送,这将更新底层数组,而不必直接调用底层数组。我尝试过访问数组原型(prototype),但不太清楚该怎么做。
这是一个代码片段来模拟我想要做的事情:
class Test {
_foo: number[];
constructor() {
this._foo = [1,2,3,4,5];
}
get foo(): number[] {
return this._foo.filter(x => {
return x > 2;
});
}
}
let obj = new Test();
obj.foo.push(6);
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
如有任何建议,我们将不胜感激。
最佳答案
通过覆盖替代:
const {create} = Object;
class Test {
_foo: number[];
_push: Object;
constructor() {
this._foo = [1,2,3,4,5];
this._push = {push: {value: this._foo.push.bind(this._foo)}};
}
get foo(): number[] {
return create(this._foo.filter(x => x > 2), this._push);
}
}
let obj = new Test();
obj.foo.push(6);
console.log(obj.foo.slice()); // 3,4,5,6
您也可以直接使用:
get foo(): number[] {
const filtered = this._foo.filter(x => x > 2);
filtered.push = this._foo.push.bind(this._foo);
return filtered;
}
或者在构造函数中将 this._push
作为函数分配一次并执行相同的操作,但这可能会在某些 JS 引擎(即 v8)中进行去优化
关于javascript - 如何添加推送到返回过滤数组的 getter 的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57776382/