为什么这里的构造函数中的“this”总是“Window”对象
Why is `this` always the `Window` object in the constructor here?
我有这个代码:
(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);
};
})();
一个小说明 - 当你创建一个类时,你不需要返回这个,因为它是隐式处理的。
相关文章:
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- 直接下载文件,而不是从window.open(url)
- ajax请求的顺序总是不同的
- Amd,希望确保某个东西总是最后执行
- $window.ga在AngularJS事件中未定义
- 如何将PDF作为二进制文件传递到window.open()
- RequireJS向模块传递配置总是返回undefined
- window.onload没有'无法在Android WebView中工作
- window.location替换并传递URL历史记录条目中的变量
- window.on.scroll事件未启动
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- 这.SOMETHING 总是返回未定义的 - extjs
- 为什么window.open不打开一个以变量形式给出的链接
- jQuery$.inArray()总是返回-1和一个对象数组
- window.location使用jquery mobile实现chrome跳转
- window.safari.pushNotification.requestPermission总是返回"拒绝
- 为什么这里的构造函数中的“this”总是“Window”对象
- cordova window.pageY偏移总是返回0
- window.onbeforeunload并不总是开火
- Safari 5 中的 $.getScript() 和 $(window).load() 并不总是有效