Trying to do this:
var c = {
x: \'other context\'
};
var o = {
x: \'this context\',
get otherContext () {
alert(this.x);
}.bind(c)
};
o.otherCon
For class proxies you might want to use something like this:
class Main {
constructor() {
this._adapter = new Adapter();
return this._createProxy();
}
_createProxy() {
return new Proxy(this, {
get(me, propertyName) {
if (typeof me._adapter[propertyName] === 'function') {
return me._adapter[propertyName].bind(me._adapter);
}
return (function () {
return me._adapter[propertyName];
}.bind(me._adapter))();
}
});
}
}
class Adapter {
constructor() {
this._foo = true;
this._yuk = 2;
}
get foo() {
return this._foo;
}
baz() {
return 4*this._yuk;
}
}
This way both, the getter and the method will be wrapped within the right context:
let main = new Main();
console.log(main.foo); // -> true
console.log(main.baz()); // -> 8
The problem is that method syntax doesn't use function expressions. It's a defined syntactic structure.
MethodDefinition[Yield] :
PropertyName[?Yield] ( StrictFormalParameters ) { FunctionBody }
GeneratorMethod[?Yield]
get PropertyName[?Yield] ( ) { FunctionBody }
set PropertyName[?Yield] ( PropertySetParameterList ) { FunctionBody }
PropertySetParameterList :
FormalParameter
Since it isn't a function expression, you don't have access to the functions methods or properties.
You can accomplish what you want with Object.defineProperty.
var proxy = { ... };
Object.defineProperty(proxy, 'left', {
get: function() {
return this.el.offsetLeft;
}.bind(this)
});