What's the difference between declaring internal variables inside a JavaScript class with this vs var?
Example:
function Foo( ) {
var tool = 'hammer';
}
function Foo2( ) {
this.tool = 'hammer';
}
One difference we're aware of is Foo2.tool will yield "hammer" whereas Foo.tool will yield undefined.
Are there other differences? Recommendations for one vs. the other?
Thanks!
there is no "one or the other" here since the purpose of the two are 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 a "public property", accessible from the outside. if i created this instance of Melee
, i can access and modify weapon
since it's open to the public.
handitem.tool
is a "private property". it's only accessible from inside the object. it is not visible, not accessible, and not modifiable (at least directly) from the outside. trying to access it will return undefined
handitem.getTool
is a "public method". since it's on the inside of the object, it has access the private property tool
and get it for you from the outside. sort of bridge to the private world.
handitem.attack
is a private method. like all private stuff, it can only be accessed from the inside. in this example, there is no way to call attack()
(so we are safe from attack :D )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With