Reputation: 29
Is any way in Javascript, how access to variable value in return function?
function x (){
return{
foo:function(text){
value= text;
}
}
}
a=x();
a.foo("some text");
Upvotes: 0
Views: 52
Reputation: 53958
Since, you haven't declared nowhere the variable value
, this variable will be declared on the global scope (as a property of the window object in the environment of a browser). So you can access it as below. However, this is bad practice, I mean to use a variable without having first declared it. This is called implied global.
function x (){
return{
foo:function(text){
value = text;
}
}
}
a=x();
a.foo("some text");
document.write(value);
Upvotes: 3
Reputation: 39
My personal opinion would be to use the object orientated approach.
var SomeObject = function(){
var text = "";
this.setText = function(value){
text = value;
};
this.getText = function(){
return text;
};
};
var myObject = new SomeObject();
myObject.setText("This is the text");
alert(myObject.getText());
Upvotes: 3