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?

3

3 Answers 3

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();

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

Another way using the Class declaration:

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


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.