1

Consider the following Java script code:

    var myObj = function (  ) {
        var x = 0;
        return {
            addup: function (y) {
                x += y;
            },
            getX: function (  ) {
                return x;
            }
        }
    }();

This function returns an object with two methods (if I am not wrong).

now, two questions:

  1. how can I call the two methods returned from the function?
  2. can those methods still have access to the variable x ?

thanks,

3 Answers 3

5
  1. myObj.getX(); and myObj.addup(5);
  2. Yes, they still have access

Example - http://jsfiddle.net/qWT9N/

Sign up to request clarification or add additional context in comments.

Comments

2

how can I call the two methods returned from the function?

myObj.addup(10);
var xValue = myObj.getX();

can those methods still have access to the variable x ? Yes

1 Comment

addup doesn't return anything.
-1

You've created "template" object myObj with private x propery and two public methods.

To create object based on your "template" call var obj = myObj();

  1. You can call them like obj.addup(2); and obj.getX();
  2. Yes those methods have access to Private x variable from them

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.