Why is this JavaScript property returning an empty string and the JavaScript function is working fine?

Consider this simple JavaScript module template:

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 is the second close working fine and the first closing not working? An example is here .

Also see this script , which proves that simple properties can be used instead of getter functions.

+4
source share
2 answers

In javascript

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

As a name, the string name: _name save the current value of _name , not a link to _name .

setName in your example will only change _name .

getName will access _name , which contains the current value.

.name will access the copied value that was set during initialization ( name: _name ).

See also SO: Javascript by reference or by value

+9
source

Try the following:

 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 assigned the value to the _name variable, and you accessed the name property of the returned object.

+2
source

All Articles