Making private members in javascript using Symbol

February 28th, 2015 admin

Quoting mozilla website:

A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol object is an implicit object wrapper for the symbol primitive data type.

So. How can we use it to achieve what we couldn't do before - creating private member in javascript.

Have a look at the example below:

var Product = (function () {
	// creating our symbol which will be our key to store private members
	var symbol = Symbol('product');
	// this object will have to store the private members
	var privateMemebers = function () {
		this.name = null;
		this.price = null;
	};
	// our class constructor
	var Product = function () {
		// this is the line where we are specifying where
		// this instance of this class will store its private members
		this[symbol] = new privateMemebers();
	};
	// prototype of our class with getters and setters operating with private mambers
	Product.prototype = {
		getName: function () {
			return this[symbol].name;
		},
		setName: function (value) {
			this[symbol].name = value;
		},
		getPrice: function () {
			return this[symbol].price;
		},
		setPrice: function (value) {
			this[symbol].price = value;
		}
	};
	return Product;
}());
 
// example
var product1 = new Product();
var product2 = new Product();
product1.setName('product1');
console.log('product1.getName()', product1.getName()); // should display 'product1'
console.log('product2.getName()', product2.getName()); // should display null
product2.setPrice(200);
console.log('product1.getPrice()', product1.getPrice()); //  should display null
console.log('product2.getPrice()', product2.getPrice());  // should display 200

That is pretty much it. This is still an experimental technology, part of the Harmony (ECMAScript 6) proposal. So be careful. Even though it is supported by Google Chrome

Posted in Uncategorized | No Comments »