benhowdle89
benhowdle89

Reputation: 37464

Why is `this` always the `Window` object in the constructor here?

I have this code:

(function() {

  function App(elements, options) {

    if (!this instanceof App) return new App(elements, options);

    var that = this;

    return this;

  }

  window.App = App;

})();

App(document.querySelectorAll('.Slider-slide'), {
  interval: 5000
});

My problem is, that it NEVER creates a new instance of App, so, this further down the code is always the Window object, any idea why??

Upvotes: 1

Views: 57

Answers (2)

megawac
megawac

Reputation: 11353

Update as stated in Musa's answer, the code can be corrected with either of these 2 patterns:

(function() {

  function App(elements, options) {

    if (!(this instanceof App)) return new App(elements, options);

    var that = this;

  }

  window.App = App;

})();

var myapp = App(document.querySelectorAll('.Slider-slide'), {
  interval: 5000
});

This class structure does not require the new call:

(function() {
    function App(elements, options) {
        var that = this;
    }

    //calling window.App(/*stuff*/) will always return a new class
    window.App = function(elements, options) {
        return new App(elements, options);
    };
})();

One small note - when you create a class you do not need to return this as this is handled implicitly.

Upvotes: 0

Musa
Musa

Reputation: 97672

Your if condition is the problem:

if (!this instanceof App)

should be:

if (!(this instanceof App))

Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table

Upvotes: 6

Related Questions