0

Was doing some dirty things to Array.prototype when I ran into this:

Array.prototype.hook_pop = function(callback) {
    var base_pop = this.pop.bind(this);  //<-- this works
    var base_pop = this.pop;             //<-- this doesn't work

    this.pop = function() {
        var ret = base_pop();
        callback(ret, this);
        return ret;
    }
}

Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".

The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • because this doesn't equal `this` in the context of the this pop function – Joe Warner May 29 '18 at 12:42
  • damn i just finished my answer – Joe Warner May 29 '18 at 12:47
  • Hmm actually, sorry - reopening. Just realised you're fiddling with the innards of an existing object, so it's a bit more complex and may merit a bit more of a specific explanation than what's in [this related question](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). – James Thorpe May 29 '18 at 12:47
  • _" "this" should point to the object through which the method is called from"_ true, but `base_pop();` doesn't invoke a method. – a better oliver May 29 '18 at 12:48

1 Answers1

0
var ret = base_pop();

In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22