目前正在尝试制作数组/对象的自定义实现(我想最终会非常相似),并且偶然发现了一个让我发疯的问题。
正如您所看到的, b 只是一个 array 的实例,即使它是从自定义类 CachedArray 创建的,因此我的自定义函数 testPush 未定义,而且我无法从所有方面找出问题所在。
使用 Nodejs 6
function _setKey(target, key, value) {
console.log('Setting value', key, 'to', value);
target[key] = value;
return true;
}
class ExtendableProxy {
constructor(a, b) {
return new Proxy(a, b);
}
}
class CachedArray extends ExtendableProxy {
constructor(redis, options) {
let RawArray = [];
super(RawArray, {
set: _setKey
});
this._rawArray = RawArray;
this.redis = redis;
this.options = options;
}
testPush() {
this.push('Its me');
}
}
var b = new CachedArray();
console.log('b instanceof CachedArray', b instanceof CachedArray); //false
console.log('b instanceof ExtendableProxy', b instanceof ExtendableProxy); //false
console.log('b instanceof Proxy', b instanceof Proxy); //false
console.log('b instanceof Array', b instanceof Array); //true
b.push('Hello.'); //Works just fine, _setKey is called and executed correctly
b.testPush(); //TypeError: b.testPush is not a function
除了我想要实现的目标之外,还有其他选择吗?本质上,我需要一个带有一些额外功能的数组,但是它有一个连接到它的代理,以便我可以进一步处理发生在我的类实例上的任何写入(因此,数组)
嗯,代理有一个处理程序,允许您挂钩与代理对象的各种交互。因此,您应该使用它来注入要添加到代理对象的任何其他方法。例如,只需提供get
因此它返回一个自定义函数,而不是将调用中继回目标:
function createCachedArray(arr) {
const customFunctions = {
testPush() {
this.push('It’s me');
},
};
return new Proxy(arr, {
set (target, property, value) {
console.log(`Setting value ${property} to ${value}`);
target[property] = value;
return true;
},
has (target, property) {
return property in customFunctions || property in target;
},
get (target, property) {
if (typeof property === 'string' && property in customFunctions) {
return customFunctions[property].bind(target);
}
else {
return target[property];
}
},
});
}
let a = [1, 2, 3];
let b = createCachedArray(a);
b.push('foo');
b.testPush();
for (const x of b) {
console.log(x);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)