Skip to content Skip to sidebar Skip to footer

Why This Javascript Property Returns Empty String, While Javascript Function Works Fine?

Consider this simple JavaScript module pattern: var human = (function () { var _name = ''; return { name: _name, setName: function (name) { _nam

Solution 1:

In Javascript

  • Strings and primitive types (boolean and numeric) are passed by value
  • Objects, arrays, and functions are passed by reference

As name is a string name: _name will store the current value of _name and not the reference to _name.

setName in your example will modify only _name.

getName will access _name which holds the current value.

.name will access the copied value which was set during the initialisation (name: _name).

See also SO: Javascript by reference vs. by value

Solution 2:

Try with this:

var human = (function () {
    var _name = '';
    var returnObj = {};
    returnObj.name = _name;
    returnObj.setName = function (name) {
        _name = name;
        returnObj.name = name;
    };

    return returnObj;
})();
human.setName('somebody');
alert(human.name);

The problem with your code was that setName was assigning a value to the _name variable and you ware accessing the name property of the returned object.

Post a Comment for "Why This Javascript Property Returns Empty String, While Javascript Function Works Fine?"