Three JavaScript Quirks That Java/C Developers Should Know

To complete the discussion about this example, the reader should be aware that either reusing the function parameter or declaring a private var inside Person and assigning the parameter to it, in both cases this value will be kept private only if it is an immutable value (a primitive). If something is it is an object or an array (so essentially something passed by reference and not by value), it will still be possible to modify it outside of the function, because assignment only perform shallow copy.

Try this to check it:

var a = [1,2,3];
var p = Person(a);  //Person {getName: function, setName: function}
p.getName();  //[1, 2, 3]
a.push(4);
p.getName();  //[1, 2, 3, 4]

To avoid this, you need to make a deep copy of the parameter you get (to this end, declaring a privateName field, although not stricly necessary, helps for clarity and readability, agreed on that).
For instance, you could try something on the line of:

function deepcopy(x) {
  return JSON.parse(JSON.stringify(x));
}
function Person(name) {
  "use strict";
  if (!(this instanceof Person)) {
    return new Person(name);
  }
  var privateName = deepcopy(name);
  
  //define privileged functions:
  this.getName = function() {
    return privateName;
  }

  this.setName = function(name) {
    privateName = deepcopy(name);
  }
  return this; 
}

This will make a deep copy of your parameter that won’t be accessible to anyone but your privileged methods.