0
function Coll(items) {
    this.removeItem = items.pop
}
const coll = new Coll([2,4,6,8,10])
console.log(coll.removeItem())

If I make console.log(coll), I can see that there's a function inside of the object. If I call it, it retuns undefined. I know the solution to make it run properly is to add () => items.pop() but I still can't understand why. The main question here is what happens when I add the () => ...() to the method call

  • 1
    For the same reason `const f = item.pop; f();` doesn't work -- it doesn't set the value of `this` to the right thing when calling `pop`. See the [linked question](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback)'s answers. Probably your best bet is `this.removeItem = () => items.pop();` but you could also use `bind` as the answers there show. See also: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – T.J. Crowder Feb 04 '22 at 12:46
  • The reason is that you're losing context. Imagine that `Array.prototype.pop` calls `this.length` in order to know the array length and know what item to remove when calling `pop()`. Having: `var items = [2, 4, 6, 8, 10];` Calling `items.pop();` makes the context (`this`) be the caller (`items`); `this.length = items.length`; - But if you only store the function reference, you will lose the context: `var a = items.pop; a()`; Unless, you create a new function with the context bound: `var a = items.pop.bind(items); a()`; – Jorge Chayan Feb 04 '22 at 13:55

0 Answers0