为什么我在使用私有 JS ES5 class 调用时会收到 Uncaught TypeError?

Why do I get an Uncaught TypeError with private JS ES5 class call?

我正在尝试在 JavaScript (ES5) 中创建一个 class。但是,当我从另一个方法调用一个方法时,我在控制台中收到以下错误消息:

Uncaught TypeError: root.abLog is not a function

有问题的违规文章(精简以仅显示相关部分)如下:

var abClass = function(options) {

    var root = this;

    this.checkAttach = function(text){
        root.abLog('Checking attached');
        /* snip */
    };

    var abLog = function(data) {
        console.log('abClass PATH: "'+vars.path+'"');
        console.log('abClass: '+data);
    };

};

root.abLog('Checking attached');this.abLog('Checking attached'); 都会导致类似的错误。

我理解的私有方法做错了什么?

在没有 rootthis 的情况下调用它,例如 -

var abClass = function(options){

   var root = this;

   this.checkAttach = function(text){
       abLog('Checking attached');
       /* snip */
   };

   var abLog = function(data) {
       console.log('abClass PATH: "'+vars.path+'"');
       console.log('abClass: '+data);
   };

};

abLog 是您的 abClass 的私有函数, this 的范围(在您的情况下附加到 root )获取您的 public class 的成员,即通过 this.XXX 直接附加的成员 - 在您的情况下,它仅 checkAttach 附加到 this(因此使其成为 public会员)

勾选 this JS bin 进行调试