The shortest form based on the answer of ADJenks:
var GlobalProxy = Proxy
Proxy = function Proxy(a,b) {
if ((typeof this != "object") || !(this instanceof Proxy)) {
return new Proxy(a,b)
}
var getLastPrototype = function(obj,parent){
var proto = Object.getPrototypeOf(obj)
if (proto !== null) {
return getLastPrototype(proto,obj)
}
return parent?parent:obj
}
Object.setPrototypeOf(getLastPrototype(a),this)
return new GlobalProxy(a,b)
}
With that it is possible to check if an Object is proxied using instanceof Proxy
.
Here are some test cases:
class DevAbstr {
devTest() {
console.log('runned devTest without problems')
return "SUCCESS"
}
}
class DevObj extends DevAbstr {}
var test = Proxy(new DevObj,{
set: function (t, k, v) {
if (k === "IS_PROXY") throw "IS_PROXY is reserved"
if (typeof t.set == "function") {
t.set(k,v)
} else {
t[k] = v;
console.log("original",t, k, v)
}
return true
},
get: function (t, k) {
if (k === "IS_PROXY") return true
if (k === "PROXIED_OBJECT") return t
if (typeof t.get == "function") {
return t.get(k)
} else {
return t[k]
}
return false
}
})
console.log("test instanceof Proxy", test instanceof Proxy) // true
console.log("test instanceof DevAbstr", test instanceof DevAbstr) // true
console.log("test instanceof DevObj", test instanceof DevObj) // true
test.blubb = 123
console.log("test.IS_PROXY", test.IS_PROXY) // true
console.log("test",test) // Proxy(Object)
console.log("test.PROXIED_OBJECT",test.PROXIED_OBJECT) // source object
console.log("test.devTest()",test.devTest()) // works
;(function() {
console.log("Proxy",Proxy)
})()
// valid!
for (var k in test) {
console.log(k+': ',test[k])
}
I also compiled this to ES5 without problems.
This approach is ugly, i knew, but it works quite well...