我有这个代码:
(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
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,它永远不会创建一个新的实例App,所以,this进一步下来的代码总是Window对象,任何想法为什么??
你的if条件是问题:
if (!this instanceof App)
Run Code Online (Sandbox Code Playgroud)
应该:
if (!(this instanceof App))
Run Code Online (Sandbox Code Playgroud)