0

Basically why I can't do this:

var a = [];
var b = a.push;
b(1);

it give's error, I know how to avoid this, but why this is not working in js?

dark_gf
  • 684
  • 5
  • 15
  • 4
    Because the value of `this` is determined at call time. However, you dissassociate the call from `a`. Therefore, there is no `this` value when `b()` (which is a reference to `Array.prototype.push` is called, so there is nothing to push *to*. – VLAZ Jul 01 '21 at 18:22
  • please post as answer so I will be able to accept it – dark_gf Jul 01 '21 at 18:30

2 Answers2

1

The this value is determined by how the function is called. You can use Function#bind to ensure the this value is set.

var a = [];
var b = a.push.bind(a);
b(1);
console.log(a);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-1

Try this:

var a = [];
var b = (param) => a.push(param);
b(1);
eagercoder
  • 526
  • 1
  • 10
  • 23