0

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");
2
  • 1
    You can't. You probably want to return it. Also, you need to declare that variable. Commented Jul 27, 2016 at 21:56
  • Assuming it was supposed to be var value ..., that's a closure, and you can't access the internal variables of a function enclosed in another function, even if it's in an object. Commented Jul 27, 2016 at 22:01

2 Answers 2

3

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());
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

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.