aawalker238
2/12/2017 - 5:34 PM

private-properties-js.js

function Person(name="John Doe", species="Alien"){
  //create a property as an object that will contain all private properties
  this.priv = {
    name,
    species
  }
  //Freeze the "this.priv" object so that these properties cannot ever be changed
  Object.freeze(this.priv);
}

Person.prototype = {
  sayName:function(){
    console.log(`sayName method: My name is ${this.priv.name}`);
  },
  saySpecies: function(){
    console.log(`saySpecies method: I am a ${this.priv.species}`);
  }
}

var person1 = new Person("Anthony", "Human");

//TESTING
console.log(person1.priv.name); //Anthony
person1.priv.name = "Tony"; //Attempting to change name property
console.log(`My name is still ${person1.priv.name}`); //"My name is still Anthony"
person1.sayName(); //"sayName method: My name is Anthony"
person1.saySpecies(); //"saySpecies method: I am a Human"