Declaring variables in a JavaScript class: this vs. var. Difference?

What is 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 of the differences we know about is Foo2.tool will give a hammer, while Foo.tool will give undefined.

Are there any other differences? Recommendations for each other?

Thanks!

+6
source share
1 answer

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)

+14
source

Source: https://habr.com/ru/post/911064/


All Articles