Miroslav Trninic
Miroslav Trninic

Reputation: 3455

Binding of this when constructor is not called in javascript

This code is a part of a constructor function body in javascript:

window.addEventListener("load", function(){
    this._updateFilter();
}.bind(this));

_updateFilter method belongs to prototype object of that constructor:

Constructor.prototype._updateFilter = function(){
    //  some code
};

I am confused with the thing that _updateFilter is called before new instance of Constructor is created. So there is no:

var obj = new Constructor();

But _updateFilter is invoked onload? Can someone explain this please ?

Thanks

Upvotes: 1

Views: 71

Answers (1)

Dan
Dan

Reputation: 63099

Simply because the listener callback or even the constructor itself is defined does not mean that it is invoked at the time it is defined. In fact, the constructor is just a function. Like any function declaration, it defines what will happen when invoked. If we don't invoke it, nothing happens. In the case of a constructor, it is invoked when we create a new instance of it. Eventually, your app will invoke the constructor and here is what will happen at that time:

  1. Using the special new keyword, we tell the JavaScript interpreter to invoke the constructor function and provide it with a new object inside of it.

  2. The interpreter sets this inside the constructor to be a reference in memory to that new object.

  3. Next, an event listener is created on the window. We pass a callback function to that listener which is a closure over the this object, making our current this reference available. But that callback does not execute yet and will not until the window's load event fires.

  4. Imagine that it did fire immediately, (i.e. was not actually a callback) we would have a problem. Even though this exists at that time and actually already inherits from Constructor.prototype, it has no such method _updateFilter. The interpreter would then check up the prototype chain and see that there is no such function on Constructor.prototype either. It would continue up the chain, not find the function, and would throw an error. But remember, the callback does not fire yet.

  5. Back to what actually does happen: Next we extend Constructor's prototype with the new method _updateFilter.

  6. So eventually the window's load event does fire and the callback really is called. The interpreter checks to see if _updateFilter exists on this, sees that it does not, and then checks up its prototype chain. Now it finds that function does exist on Constructor.prototype, and runs that code.

Upvotes: 1

Related Questions