简体   繁体   中英

Why does this inner function return undefined?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM