oop - Encapsulation / Data Hiding in Javascript? -
i understand concept of encapsulation in javascript, , how make properties , methods public or private.
i'm playing around example:
var person = function(newname, newage) { // private variables / properties var name = newname; var age = newage; // public methods this.getname = function() { return name; } // private methods var getage = function() { return age; } // public method, has acces private methods this.giveage = function() { return getage(); } } var jack = new person("jack", 30); console.log(jack.name); // undefined console.log(jack.getname); // jack console.log(jack.getage()); // typeerror: jack.getage not function console.log(jack.getage); // undefined console.log(jack.giveage()); // 30 so, variables var name , var age private. access them use public methods using .this reference. var inside function private, , that's .this inside object visible outside.
i guess that's cause person visible, exposes of properties.
am on right track? right way hide or expose properties / methods?
and 1 more question, why console.log(jack.getage()); throws error? , when referencing functions "stored" in variables, should put () @ end of function, works both ways, don't know use?
thanks!
i guess that's cause person visible, exposes of properties.
correct.
am on right track? right way hide or expose properties / methods?
if want it, yes, standard way it. there's @ least 1 other way of es2015, (probably) more overhead.
and 1 more question, why console.log(jack.getage()); throws error?
because jack object doesn't have getage property, jack.getage yields undefined, isn't function. there's getage variable inside context giveage closure has access (along age , name), jack doesn't have getage property.
and when referencing functions "stored" in variables, should put () @ end of function, works both ways, don't know use?
no, doesn't work both ways. jack.getname gets reference function. jack.getname() calls function , gets return value.
i should note there's no point getage function. it's accessible closures defined within person function, age , name are. use getage use age instead , avoid function call.
just completeness, i'll note many people don't worry private properties in javascript, opting instead "private convention" — e.g., use naming convention (such names starting _) mean "don't touch these, they're private." doesn't prevent people using them, of course, indicates shouldn't. folks advocating point out in many languages "true" private properties/fields (java, c#), properties/fields accessible small amount of effort via reflection. , so, argument goes, using naming convention "as private."
i'm not agreeing (nor particularly disagreeing) that, require rather more work in java or c# access private properties public ones. i'm noting "private convention" approach quite common, , "good enough."
Comments
Post a Comment