Why this JavaScript property returns empty string, while JavaScript function works fine?

梦想的初衷 提交于 2021-01-27 07:22:29

问题


Consider this simple JavaScript module pattern:

var human = (function () {
    var _name = '';
    return {
        name: _name,
        setName: function (name) {
            _name = name;
        }
    }
})();
human.setName('somebody');
alert(human.name); // shows an empty string
human = (function () {
    var _name = '';
    return {
        name: function() {
            return _name;
        },
        setName: function (name) {
            _name = name;
        }
    }
})();
human.setName('somebody');
alert(human.name()); // shows 'somebody'

Why the second closure works fine, while the first closure is not working? See example here.

Please also see this fiddle, which proves that simple properties can be used instead of getter functions.


回答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




回答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.



来源:https://stackoverflow.com/questions/14707532/why-this-javascript-property-returns-empty-string-while-javascript-function-wor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!