Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to declare functions within a Javascript class?

Tags:

javascript

I'm trying to understand the difference between 2 different function declarations in JavaScript.

Consider the following code snippet:

function SomeFunction(){

   this.func1 = function(){
   }

   function func2(){
   }
}

What is the difference between the declarations of func1 and func2 above?

like image 758
JohnB Avatar asked May 24 '17 04:05

JohnB


1 Answers

In simple language, fun1 is a property of SomeFunction class holding a reference of anonymous function where func2 is named function.

Property

Here fun1 is property of that SomeFunction class, it means when you create instance of SomeFunction class using new keyword, then only you can access it from outside.

Private Method

Here fun2 will work as private method of class SomeFunction, and will be accessible inside that class only.


Sample

function SomeFunction() {
  this.func1 = function() { console.log("in func1") }
  function func2() { console.log("in func2") }
}

var obj = new SomeFunction();

obj.func1();  //Accessible 
obj.func2(); //Not accessible
like image 109
Laxmikant Dange Avatar answered Sep 22 '22 15:09

Laxmikant Dange