考虑这段代码:
app.mediaLibrary = new function MediaLibrary() {
var self = this;
self.media = new Proxy([], {
set(target, key, value) {
console.log(`Setting value ${key} as ${value}`)
if (!(value instanceof self.Media))
throw new Error(`${value} is not instance of Media.`)
target[key] = value;
return true
},
get (target, key) {
console.log(`Getting value ${key} as ${target[key]}`)
return target[key]
}
});
self.Media = function Media(file, fileReader) {
this.src = fileReader.result;
this.file = file;
}
return self;
}
每当我app.mediaLibrary.media.push(new app.mediaLibrary.Media("", ""))
在控制台中调用时,我都会看到:
Getting value push as function push() { [native code] }
Getting value length as 0
Setting value 0 as [object Object]
Setting value length as 1
Uncaught Error: 1 is not instance of Media.(…)
我明白为什么我会看到这个,但我该如何围绕它进行编码?看来我的陷阱是由内部(push
,length
)以及外部调用([0]=...
)触发的,我不知道如何区分它们。有任何想法吗?