2

我在使用 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);
    }
}
4

0 回答 0