mrspoonzy at gmail Cube by Noah Ellman A powerful javascript toolkit, in research © by Noah Ellman

Coding Practices That Annoy Me

  • When people prefix variables with underscores as if they are private

It is quite annoying when javascripters pretend that by prefixing their variables with underscores _ they are somehow magically making them private, or protected variables. Firstly, umm no. I can illegally access your underscored method anytime if I desired too. Secondly, underscores are really annoying to look at, and doubly annoying to type over. Stop with the underscores! There are better ways. . .

How to create a real javascript private variable?

var MyClass = (function(){

	//constructor
	var klass = function() { }; 

	// a private variable that is really hidden
	var privateVariable = { };

	// a public method
	// it is allowed to access the above private var, but nobody outside of here can
	klass.prototype.getPrivateVariable = function() {
		return privateVariable;
	};

	// Return and expose your new class
	return klass;

})();

var abc = new MyClass();
abc.privateVariable // DOESNT EXIST AND WON'T WORK
abc.getPrivateVariable() // WORKS

// Furthermore
typeof abc.privateVariable == "undefined"  // This is true

Discussion on /blog-javascript-bad-coding-styles




itoa('1281863294') 02/17/17 :  

That is true, this would be a for singleton then.


weapon_crowbar 11/05/14 :  

There's a problem with this approach. var MyClass = (function(){ var privateVariable = { }; var klass = function (initValue) { privateVariable = initValue; }; klass.prototype.getPrivateVariable = function() { return privateVariable; }; return klass; })(); var abc = new MyClass('test1'); var cba = new MyClass('test2'); console.log(abc.getPrivateVariable()); // Outputs 'test2' console.log(cba.getPrivateVariable()); // Outputs 'test