Javascript 为什么这里构造函数中的'this'总是'Window'对象?
我有以下代码:Javascript 为什么这里构造函数中的'this'总是'Window'对象?,javascript,Javascript,我有以下代码: (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'), {
(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
});
我的问题是,它从不创建应用程序的新实例,因此,这个再往下的代码总是窗口
对象,你知道为什么吗???更新如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
});
此类
结构不需要新建
调用:
(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);
};
})();
一个小提示-当您创建一个类时,您不需要返回它,因为它是隐式处理的。更新如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
});
此类
结构不需要新建
调用:
(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);
};
})();
一个小提示-当您创建一个类时,您不需要返回它,因为它是隐式处理的。您的if条件是问题:
if (!this instanceof App)
应该是:
if (!(this instanceof App))
如果问题出在您的条件下,请查看:
if (!this instanceof App)
应该是:
if (!(this instanceof App))
请看一下,因为您没有使用新的应用程序初始化应用程序call@megawac没有必要:我在答案中提供了一个例子,它将在@Benhowdle89使情况变为真实,因为您没有使用新的应用程序初始化应用程序call@megawac没有必要:我在回答中提供了一个例子,这将使情况变得真实@benhowdle89@benhowdle89对我最初误读了代码,我更新了answer@benhowdle89是的,我最初误读了代码,我更新了答案