Question

I have the following java script code

var obj = (function(){
    var privateVariable1 = 5;

    function privateFunction(){
        alert(privateVariable1);
    }

    obj1 = {};
    obj1.publicVariable = privateVariable1;
    obj1.publicFunction = function(){
        privateFunction();
    }

    return obj1;

}());


alert(obj.publicFunction());

It alert's 5 and undefined. I did not understood why it alert's undefined also. Can anyone tell me why this behavior is happening?

Était-ce utile?

La solution

Functions return undefined by default in javascript, and you're not returning anything from obj.publicFunction() so it returns undefined, which is what is alerted when you do

alert(obj.publicFunction());

Autres conseils

Both publicFunction and privateFunction don't return a value.

Change to:

var obj = (function(){
    var privateVariable1 = 5;

    function privateFunction(){
        alert(privateVariable1);
        return privateVariable1;
    }

    obj1 = {};
    obj1.publicVariable = privateVariable1;
    obj1.publicFunction = function(){
        return privateFunction();
    }

    return obj1;

}());

It is alerting 5 because in the publicFunction you call privateFunction, which will alert the privateVariable1 (which is 5 in this case). Because you call your function in an alert, and the publicFunction doesn't return anything, it will return undefined.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top