1

I do this

function myFunction() {
    var myVar = "I think I am encapsulated";

    function getMyVar() {
        return myVar;
    }
}

var myProperty = myFunction;
myProperty.getMyVar();  // tells me myProperty.getMyVar is not a function.

and

function myFunction() {
    var myVar = "I think I am encapsulated";

    function getMyVar() {
        return myVar;
    }
}

var myProperty = myFunction();
myProperty.getMyVar();   // tells me myProperty is undefined

and even

function MyFunction() {
    var myVar = "I think I am encapsulated";

    function getMyVar() {
        return myVar;
    }
}

var myProperty = new MyFunction();
myProperty.getMyVar();  // tells me myProperty.getMyVar is not a function.

and in all three cases I get problems. I have included the problem as in line comment in all three sections. Now, before someone tells me to just use a closure, I am not trying to understand closures, I am trying to understand exactly what happens with inner functions.

If you can explain above, I would grateful. Because it is counter intuitive to me.

Thanks

dublintech
  • 16,815
  • 29
  • 84
  • 115

2 Answers2

5

What you did is just define a function inside myFunction, creating a closure ...

To remedy the implementation, make getMyVar an instance member:

function myFunction() {
    var myVar = "I think I am encapsulated";

    this.getMyVar = function () {
        return myVar;
    }
}
Alex
  • 34,899
  • 5
  • 77
  • 90
  • Thanks. Excuse my pedantry but this also creatse a closure because it is also defining a function inside myFunction - albeit an anonymous one. – dublintech Mar 22 '12 at 20:21
2

You aren't exposing the getMyVar function.

You want:

function myFunction() {
    var myVar = "I think I am encapsulated";

    this.getMyVar = function() {
        return myVar;
    }
}

However, myVar is also locally scoped to the function execution... and the funciton hasn't been executed.

The last lines need to be

(new myFunction()).getMyVar(); 

EDIT: Though perhaps all you're looking for is pseudo-namespacing? In which case you can do:

var myObject = { 
    myProperty: "value",
    myFunction: function() { }
}

Or, more likely you're trying to make myVar act like a private member, in which case you can do:

var myObject = function() {
    var myVar = "I think I am encapsulated";

    return { 
        getMyVar: function() {
            return myVar;
        }
    }
}(); //self-executing function
Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79