使用JavaScript对象在另一个文件中调用JavaScript函数

时间:2017-03-30 16:20:34

标签: javascript jquery

我想从另一个JavaScript文件中调用一个JavaScript函数

下面是我的代码:

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

当我调用函数

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

为什么我会收到coolmethod未定义的错误?

3 个答案:

答案 0 :(得分:1)

要使它可以从外部访问,您需要使用父函数的this引用来定义子函数,如下所示:



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

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




答案 1 :(得分:0)

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

这基本上转化为:

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

正如您所看到的,coolMethod只是一个指向函数的局部变量。

使用:

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

因此coolMethod成为exJS的成员。

答案 2 :(得分:0)

使用Class声明的另一种方法:

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


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