1

我有这个代码:

(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
});

我的问题是,它永远不会创建 的新实例App,因此,this更进一步的代码始终是Window对象,知道为什么吗?

4

2 回答 2

6

您的 if 条件是问题所在:

if (!this instanceof App)

应该:

if (!(this instanceof App))

看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table

于 2013-10-20T16:31:45.190 回答
0

如 Musa 的回答中所述进行更新,可以使用以下两种模式中的任何一种来更正代码:

(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
});

class结构不需要new调用:

(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);
    };
})();

一个小提示 - 当您创建一个类时,您不需要返回它,因为这是隐式处理的。

于 2013-10-20T16:30:58.737 回答