RooSoft RooSoft -4 years ago 116
Node.js Question

How can a function in a javascript hash call another one in the same hash safely

Here is a javascript/ES6 method returning a hash consisting of two methods... writeA and _write. We want to call writeA from outside of the hash, and this method has itself to call _write, defined just below, to get its job done.

getHash = () => {
return {
writeA: () => {
console.log(this);
this._write('a');
},
_write: (value) => {
console.log(value);
}
};
};

getHash().writeA();


When the last line gets executed, the interpreter says that this._write is not a function. _write has the same effect. How can I refer to _write from within writeA?

Answer Source

You're using => for your function definitions, which completely changes the way this binding works. Functions created with => are bound with this as what it was in the environment (scope) in which they were created. Since getHash() itself is an => function, the value of this in the context where getHash is defined will be what's visible in writeA().

If you go through the return value from getHash() and rewrite the functions with function() syntax, you'll get the behavior you expect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download