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?
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
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