0

I want to call one JavaScript function from another JavaScript file

below is my code:

 var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }

when I call the function

var myClass = new exJS();
myClass.coolMethod();

Why do I get the error that coolmethod is not defined?

Vickel
  • 7,879
  • 6
  • 35
  • 56
Surajghosi
  • 226
  • 1
  • 2
  • 9
  • Take a look at the javascript Module pattern! – funcoding Mar 30 '17 at 16:23
  • Google: "define class javascript". First result: https://www.phpied.com/3-ways-to-define-a-javascript-class/ – dgiugg Mar 30 '17 at 16:24
  • Possible duplicate of [How do you create a method for a custom object in JavaScript?](http://stackoverflow.com/questions/504803/how-do-you-create-a-method-for-a-custom-object-in-javascript) – Heretic Monkey Mar 30 '17 at 16:28

3 Answers3

1

For it to be accessible externally, you need to define the child function using the this reference of the parent function, like this:

var exJS = function() {
  this.coolMethod = function() {
    alert("hello suraj");
  }
}

var myClass = new exJS();
myClass.coolMethod();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0
 var exJS = function (){
  function coolMethod() {
    alert("hello suraj");
   }
}

this essentially translates to :

 var exJS = function (){
  var coolMethod = function () {
    alert("hello suraj");
   };
}

as you can see coolMethod is just a local variable pointing to a function.

use :

this.coolMethod = function () {
        alert("hello suraj");
       };

so coolMethod becomes a member of exJS.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

Another way using the Class declaration:

class exJS {
    coolMethod () {
    alert("hello suraj");
  }
}


var myClass = new exJS();
myClass.coolMethod();
funcoding
  • 741
  • 6
  • 11