0

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?

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
  • Can you also include how you instinciate your `abClass` as well as how you call your `abLog` method? – M0nst3R Sep 12 '19 at 12:49
  • 1
    abLog has nothing to do with `this` hence the error. variables defined inside of a block are not part of `this` – epascarello Sep 12 '19 at 12:50
  • 1
    It is not global, it is scoped to that block. – epascarello Sep 12 '19 at 12:52
  • 1
    Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Jared Smith Sep 12 '19 at 12:54
  • Disregard previous comment - it looks like we are looking at this from two ways - one way being that the call of the function is wrong (and doesn't match the definition) and the other being that the definition is wrong (and doesn't match the call). – Lewis Sep 12 '19 at 12:59

1 Answers1

3

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

Vandesh
  • 6,368
  • 1
  • 26
  • 38