properties - Why this JavaScript property returns empty string, while JavaScript function works fine? - Stack Overflow

Consider this simple JavaScript module pattern:var human = (function () {var _name = '';retur

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.

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.

Share Improve this question asked Feb 5, 2013 at 12:25 user1968030user1968030
Add a ment  | 

2 Answers 2

Reset to default 8

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744647298a4585690.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信