0

I have a simple prototypal inheritance constructor, which I'm using arrow functions for.

app.Node = function (name, type) {
    this.name = name;
    this.type = type;
    this.children = [];
}

app.Node.prototype = {
    addChild: (child)=>{
        child._parent = this;
        this.children.push(child);
    },
    removeChild: (child)=>{
        this.children.forEach((item, i) => {
            if (item === child) {
                this.removeChildAtIndex(i);
            }
        });
    },
}

However, due to the nature of this and arrow functions, the value of this is undefined within the prototype methods above. So am I able to use arrow functions in this way? I can't figure out what I'd need to change, other than to use normal function functions.

shrewdbeans
  • 11,971
  • 23
  • 69
  • 115
  • You nailed the difference between arrow and normal functions pretty well. Arrow functions aren't just shortcuts. In your particular case a shortcut for method can be used instead, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions – Estus Flask Dec 02 '16 at 13:58

1 Answers1

2

So am I able to use arrow functions in this way?

No. Arrow functions capture the value of this from when they are declared.

I can't figure out what I'd need to change, other than to use normal function functions.

Do that. Use the right tool for the job.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335