How Javascript Encapsulation is possible?

If we are planning to perform inheritance over private and public methods then Javascript encapsulation is not possible. But we can always do encapsulation using Javascript closures. Following is a code snippet of encapsulation in Javascript using closures.
function objectEncapsulation() {
  var carBrand = 'BMW';

  return {
    setCarBrand : function() {
      carBrand = 'Tesla';
    },
    getCarBrand : function() {
      return carBrand;
    }
  };
}

var newObj = new objectEncapsulation();
console.log(newObj.carBrand);
newObj.setCarBrand();
console.log(newObj.getCarBrand());
console.log(newObj.carBrand);

Output

undefined
Tesla
undefined

Comments