Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top