我遇到了JavaScript“严格模式”的问题。我正在编写我的库构造函数,但是当我在我的库的开头启用严格模式时,"use strict";
我收到此错误 - Uncaught TypeError: Cannot set property 'e' of undefined
。以下是我的构造函数代码: -
(function(window, document, undefined){
"use strict";
function Ram(CSSselector) { //The main Constructor of the Library
if (this === window) { return new Ram(CSSselector); }
if ((CSSselector !== undefined) && (typeof CSSselector === "string")) {
this.e = catchEl(CSSselector);
} else {
this.e = CSSselector;
}
this.cssSel = CSSselector;
}
}(this, this.document));
感谢@Dave ,我能够通过以下方式解决问题: -
function Ram(CSSselector) { //The main Constructor of the Library
if (this === window) { return new Ram(CSSselector); }
//This code helps to call the constructor without the new keyword!
//Thanks to Dave for help!
if (this instanceof Ram) {
this.e = ((CSSselector !== undef) && (typeof CSSselector === "string")) ? catchEl(CSSselector) : CSSselector;
this.cssSel = CSSselector;
} else {
return new Ram(CSSselector);
}
}