patternjavascriptMinor
this scope for parent object within inner object
Viewed 0 times
thisparentwithinscopeforobjectinner
Problem
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.
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'Solution
I understand that you are just experimenting with closures, because your code should be a simple geter like that...
This does the same as your example:
[edit]
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;
}
});Code Snippets
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'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'var object = {}
(function(){
var _name='foo';
object.getName=function(){
return _name;
}
});Context
StackExchange Code Review Q#3121, answer score: 4
Revisions (0)
No revisions yet.