there is no βone or the other,β since the purpose of two is different.
consider this:
var Melee = function(){ //private property var tool = 'hammer'; //private method var attack = function(){ alert('attack!'); }; //public property this.weapon = 'sword'; //public methods this.getTool = function(){ return tool; //can get private property tool }; this.setTool = function(name){ tool = name; //can set private property tool }; }; var handitem = new Melee(); var decoration = new Melee(); //public handitem.weapon; //sword handitem.getTool(); //hammer handitem.setTool('screwdriver'); //set tool to screwdriver handitem.getTool(); //is now screwdriver //private. will yield undefined handitem.tool; handitem.attack(); //decoration is totally different from handitem decoration.getTool(); //hammer
handitem.weapon
in OOP is "public property" accessible from the outside. if I created this instance of Melee
, I can access and modify the weapon
as it is open to the public.
handitem.tool
is a "private property". it is accessible only from inside the object. it is not visible, inaccessible and is not modified (at least directly) from the outside. an attempt to access it will return undefined
handitem.getTool
is a "public method". since it is located inside the object, it has access to the private property of the tool
and gets it from the outside for you. view of the bridge to the private world.
handitem.attack
is a private method. like all private items, it can only be accessed from within. in this example there is no way to call attack()
(so that we are safe from the attack: D)
source share