为什么这里的构造函数中的“this”总是“Window”对象

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

本文关键字:总是 Window 对象 这里 this 为什么 构造函数      更新时间:2023-09-26

我有这个代码:

(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对象,知道为什么吗?

您的 if 条件是问题所在:

if (!this instanceof App)

应该是:

if (!(this instanceof App))

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

更新 如 Musa 的回答中所述,可以使用以下 2 种模式之一更正代码:

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

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