1

Why doesn't the last line of this code work? How can I make it work without changing Thing or obj? How can I assign a context-bound function invoking 'obj.getName' to the variable 'f' (that is, the expression 'f()' would result in the invocation of 'obj.getName').?

class Thing{
  constructor(name) {this._name = name;}
  getName() { return this._name;}
}

const obj = new Thing('a');
const f = obj.getName;
const name = f();
McLovin
  • 11
  • 3
  • 3
    You need to bind it explicitly: `const f = obj.getName.bind(obj);` – zerkms Oct 23 '18 at 19:55
  • Possible duplicate of [Maintaining the reference to "this" in Javascript when using callbacks and closures](https://stackoverflow.com/questions/7874723/maintaining-the-reference-to-this-in-javascript-when-using-callbacks-and-closu) – Heretic Monkey Oct 23 '18 at 20:13

1 Answers1

1

This is just explaining why it doesn't work, the solution is already in the comments.

Why doesn't the last line of this code work

let's break it down to understand it more clearly.

In this line

const f = obj.getName;

You're copying the function getName definition, and setting it to f.

f now is a normal function like any you would define.

let f = function getName() {
  return this._name;
}

Now if you'd call that, wouldn't this be undefined ?

Zohini
  • 6,236
  • 3
  • 10
  • 27