Is this the best way to get access to the parent scope when dealing with complex objects literals?
I find this a bit ugly, and obviously the best solution would never be involving calling it by name directly, but by saving the state of the previous scope. I tried it with bind() but didn't get it to work properly.
var object = {
name : 'foo',
getName : (function(){
return function(that){
return {
a : 111,
b : that.name,
c : function(){
return this.b;
}
}
}(this);
})
};
object.getName().b // 'foo'
1 Answer 1
I understand that you are just experimenting with closures, because your code should be a simple geter like that...
var object = {
name : 'foo',
getName : function(){ //closure
return {
a : 111,
b : this.name, // variable th is avaliable in the inner scope
c : function(){
return this.b;
}
}
}
};
object.getName().b // 'foo'
This does the same as your example:
var object = {
name : 'foo',
getName : (function(){ //closure
var th=this; // a new var introduced in a closure
return function(){
return {
a : 111,
b : th.name, // variable th is avaliable in the inner scope
c : function(){
return this.b;
}
}
}();
})
};
object.getName().b // 'foo'
[edit]
this
in JS depends on where the function is called as well, so if you want a nice encapsulation Try this:
var object = {}
(function(){
var _name='foo';
object.getName=function(){
return _name;
}
});
-
\$\begingroup\$ is it possible to make 'getName' an object by itself that has access to the parent object, without the need to invoke the function on every call? \$\endgroup\$vsync– vsync2011年06月26日 12:32:21 +00:00Commented Jun 26, 2011 at 12:32
-
\$\begingroup\$ There are at least two totally different ways (except yours) to do it. But I still don't see why
getName
should be an object. It looks like a simple getter function and it should be one. \$\endgroup\$naugtur– naugtur2011年06月26日 13:30:40 +00:00Commented Jun 26, 2011 at 13:30 -
\$\begingroup\$ this is just an example code, and it seems that i picked the wrong names.. lets call it 'a' and 'b' then, instead of 'name' and 'getName' \$\endgroup\$vsync– vsync2011年06月26日 13:37:47 +00:00Commented Jun 26, 2011 at 13:37
-
\$\begingroup\$ Then I'd say that my second example - caching the correct
this
in a variable and managing its scope - suits your case. But i don't recommend using this keyword and trying to simulate object-oriented coding in JS. It might hurt some day. \$\endgroup\$naugtur– naugtur2011年06月26日 14:26:56 +00:00Commented Jun 26, 2011 at 14:26