Search code examples
javascriptecmascript-5

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


I am attempting to make a class in JavaScript (ES5). However, when I call one method from another, I get the following error message in console:

Uncaught TypeError: root.abLog is not a function

The offending article in question (stripped down to show only the relevant parts) is as follows:

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

};

Both root.abLog('Checking attached'); and this.abLog('Checking attached'); result in similar errors.

What have I done wrong with what I understand is a private method?


Solution

  • Call it without root or this like -

    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 is a private function of your abClass and the scope of this (attached to root in your case) gets a copy of your public members of the class, i.e. members directly attached via this.XXX - In your case, it's only checkAttach attached to this (hence making it a public member)

    Check this JS bin to play around and debug