4
\$\begingroup\$

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'
asked Jun 26, 2011 at 11:01
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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;
 }
});
answered Jun 26, 2011 at 12:01
\$\endgroup\$
4
  • \$\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\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented Jun 26, 2011 at 14:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.