Trying to do this:
var c = {
x: 'other context'
};
var o = {
x: 'this context',
get otherContext () {
alert(this.x);
}.bind(c)
};
o.otherContext;
But I get a Syntax Error
:
Uncaught SyntaxError: Unexpected token .
A use-case
You may ask, why I may want to change context on a getter. The use case that led me here dealt with creating a helper object that would retrieve DOM properties. The helper was defined inside another object that held a reference to the DOM element I needed properties from. So, this helper object is really just a proxy for some DOM methods, really, and I would do something like:
var ViewObject = function () {
this.el = document.getElementById('id');
var proxy = {
...
get left() {
return this.el.offsetLeft
}.bind(this)
...
};
};
IMHO this is a pretty valid use-case. And one where having the parent object's this
context would be useful. (Maybe proxy functions may be more adequate? Hmm...I didn't think about that. Still getters are ES5 and proxies are ES6 and only implemented by evergreens and Edge 13+, I think in the scope of ES5 the question still very much applies.)