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:
handitem.weaponin OOP is a “public property”, accessible from the outside. if i created this instance ofMelee, i can access and modifyweaponsince it’s open to the public.handitem.toolis 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 returnundefinedhanditem.getToolis a “public method”. since it’s on the inside of the object, it has access the private propertytooland get it for you from the outside. sort of bridge to the private world.handitem.attackis a private method. like all private stuff, it can only be accessed from the inside. in this example, there is no way to callattack()(so we are safe from attack 😀 )