Example:
let foo = {bar: 'baz', method() { this.bar = 'baz2' }}
let fooProxy = new Proxy(foo, {set(target, key, val) { console.log('set trap triggered!') }})
fooProxy.bar = 'any value' // as expected: set trap triggered!
foo.method() // trap not triggered
为什么会出现这种情况?即使是从目标对象内部,如何强制触发陷阱?
编辑,主要是为了向@Bergi解释这一点:
我的主要目标是拦截 foo 对象的任何更改,因此我可以设置属性,例如foo. 更改为 true。另外,我想拦截对 foo 具有数组/对象类型的属性的更改。你知道,如果我设置 foo 的属性,一切都很好,但是当我例如推送到一个数组,然后代理无法拦截它。所以我也需要将数组/对象属性转换为代理(我将它们称为 ArrayProxy 和 ObjectProxy)。
这是我的代码(打字稿):
// Category.ts
class Category extends Model {
title: string = ''
products: Product[] = []
}
// Model.ts
abstract class Model extends BaseModel {
constructor() {
return new Proxy(this, {
set (target, key, val) {
if (Array.isArray(val) {
target[key] = new ArrayProxy(val) // I WANT all array properties to be ArrayProxy but the problem (see below) not let me do that
}
}
})
}
}
// BaseModel.ts
abstract class BaseModel {
constructor(attributes) {
this.setAttributes(attributes)
}
setAttributes(attributes) {
Object.keys(attributes).forEach((key) => {
this[key] = attributes[key] // THE PROBLEM
})
}
}
我已经删除了代码,但这并不重要(例如对象属性和 ObjectProxy 的类似情况)。
如果有更优雅的方式来完成我所做的事情,我将非常感激。