0

I have one doubt about javascript which I hope someone can explain me. I have a Watcher class which works just as expected:

function Watcher(paths) {
    let watcher_instance = Object.create(Watcher.prototype);
    watcher_instance.paths = paths;
    return watcher_instance;
}


Watcher.prototype = {
    init_watcher() {
        console.log(this.paths)
    }
}

Then, when I do

let watcher = new Watcher(paths);
watchers.init_watcher();  // prints the paths Array

all works as expected.

But I change the prototype to:

Watcher.prototype = {
    init_watcher: () => {
        console.log(this.paths) // prints undefined
    }
}

this.path seems not to be initialized at all. Anybody knows why?

I've read this, but haven't seen any reference to this behaviour.

  • Read also `arrow functions`. It's cause, why you got `undefined` – Suren Srapyan Dec 29 '17 at 10:29
  • 1
    "An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for *non-method* functions, and they cannot be used as constructors." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Yury Tarabanko Dec 29 '17 at 10:30
  • Thanks! Indeed, this works just fine: Watcher.prototype = { init_watcher: function() { console.log(this.paths) } } – Victor Diez Dec 29 '17 at 10:37

0 Answers0