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;
}
});
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'
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;
}
});
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'