Asked 7 years ago
14 Jan 2017
Views 1364
lain

lain posted

how to set private property in JavaScript ?

how to set private property in JavaScript ?

trying to make private property name in Product


var Product = (function() {
    var  name;
    function Product(name) {
        this.name = name;
    }
    Product.prototype.getName = function() {
        return this.name;
    };

    return Product;
}()); 
var product = Product ('Apple');
console.log(product.getName());//Apple
delete product.name;//true
console.log(product.getName());//undefined


i able to delete product.name . it means its not private key so how to set private property in JavaScript ?
Rasi

Rasi
answered Nov 30 '-1 00:00

use Symbol to make private property of object



var Product= (function() {
    var nameSymbol = Symbol('name');

    function Product(name) {
        this[nameSymbol] = name;
    }

    Product.prototype.getName = function() {
        return this[nameSymbol];
    };

    return Product;
}());
var product = Product ('Apple');
console.log(product.getName());//Apple
delete product.name;//true
console.log(product.getName());//Apple


when we use Symbol we cant able to delete property product.name or delete product.nameSymbol (try to delete Symbol ) but still we get result at product.getName()
yogi

yogi
answered Nov 30 '-1 00:00


use let statement to make private property

let statement make available to local scope only , by that we can make the private property.

var Constructor
{
    let privateScope = {};

    SomeConstructor = function SomeConstructor () {
        this.someProperty = "me publicly aviliable ";
        privateScope.hiddenProperty = "me private , sorry not aviliable";
    }

    SomeConstructor.prototype.showPublic = function () {
        console.log(this.someProperty); // me publicly aviliable
    }

    SomeConstructor.prototype.showPrivate = function () {
        console.log(privateScope.hiddenProperty); // me private , sorry not aviliable
    }

}

var obj = new SomeConstructor();

obj .someProperty ;// me publicly aviliable
obj .privateScope.hiddenProperty;//undefined
 


when you try to access hiddenProperty . it will return undefined because by let statement hiddenProperty only available that local scope , not available globally
if you change let privateScope = {}; with var privateScope = {}; it become private to public and available out of function , become global
ravi

ravi
answered Nov 30 '-1 00:00

Module Pattern in JavaScript


 var counter = (function(){
  var i = 0;

  return {
    get: function(){
      return i;
    },
    set: function( val ){
      i = val;
    } 
 
  };
}());

counter.get(); // 0
counter.set( 3 )//3
counter.get(); // 3
counter.i;//undefined


function return object and we cant able to get object 's property . it become private for current function
its work as singleton pattern
Post Answer