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:
- Using the
newoperator sounds like too classical OOP. - Defining
class Obusingfunctionisn’t intuitive (at least in the beginning).
That’s why I am trying to define ob with an 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)?
Following Douglas Crockfords simple constructor pattern, I would make a constructor-function that uses the object literal instead of new. Like this: