I have the following:
var o = {f: function(fn) {
fn.call(o);
}};
var ob = {f: function() {
o.f(function() {
this.x = 2; //HERE: how can this reference ob?
//ob.x = 2;
});
}};
ob.f();
ob.x; // undefined
o.f(fn)
calls fn where this is bound to o.
At HERE, I want to use this to access ob.
However, when ob.f
is called, this is bound to o.
JQuery works like this, I think.
For example:
$(...).blah(function() {
this // this is bound to $(...) jquery object.
...
};
What I'm doing now is:
var Ob = function() {
var self = this;
self.f = function() {
o.f(function() { self.x = 2; };
};
};
var ob = new Ob();
ob.f();
ob.x; // 2
But I don't like above for stylistic reasons:
- new operator sounds like too classical oop.
- defining class Ob using function isn't intuitive (at least in the beginning).
That's why I am trying to define ob with object literal. But I can't find a way to reference the object, ob, in a function that uses method call that sets this to other object than ob.
I can do something like the following:
var ob = {f: function() {
o.f(function() {
self.x = 2;
});
}};
var self = ob;
ob.f();
ob.x;
But I don't know how to factor above. I tried:
function obj(o) {
return function() {
var self = o;
return o;
}();
}
var ob = obj({f: function() {
o.f(function() {
self.x = 2;
});
}});
ob.f();
ob.x;// ReferenceError: self is not defined
So, is there a way to reference the object in a function inside the object reliably (this can bound to anything depending on the context)?