0

Hopefully, this is a simple answer. I am trying to call a method from inside my object, however, the console is throwing an error that the function is not a function.

function tabs(el, data){
    this.el = el;

    this.addTab = function(data){
        console.log("addTab", this.el, data);
    };

    data.forEach(function(data){
        this.addTab(data);
    });
}

I am calling my object initially like so:

var t = new tabs("tabs", []);

My error is that addTab is not a function.

Ryan Peterson
  • 132
  • 1
  • 9

1 Answers1

1

Each function has it's own context which this inside it refers to. The context of the function which you have passed to the forEach does not refer to the object itself. So you need to keep the context of your function to refer to the current object. Change the function declaration with arrow function to preserve the outer context.

function tabs(el, data){
    this.el = el;

    this.addTab = function(data){
        console.log("addTab", this.el, data);
    };

    data.forEach((data) => {
        this.addTab(data);
    });
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • An explanation as to *why* that makes a difference would make this a better answer. – Quentin Oct 19 '17 at 11:04
  • Thanks for this. I was not aware of the additional features of arrow functions. I'm wondering though why using addTab (and not this.addTab) from inside the original code also will not work? – Ryan Peterson Oct 19 '17 at 11:08
  • Because `addTab` is bounded to the current object. So you need to find that object than call `addTab` from it – Suren Srapyan Oct 19 '17 at 11:10
  • I see now. I've set a var self = this in the original tabs function, then called self.addTab instead of this.addTab or arrow function and looks to be working. – Ryan Peterson Oct 19 '17 at 11:13
  • Yes, the `magic :D` is under the `this` keyword, because it is served keyword. With another name you can force to work – Suren Srapyan Oct 19 '17 at 11:14