无法设置属性";“什么?”;未定义的。JavaScript的问题;严格模式;!
我在使用JavaScript“严格模式”时遇到问题。我正在编写我的库构造函数,但是当我在库的开头启用strict模式时,无法设置属性";“什么?”;未定义的。JavaScript的问题;严格模式;!,javascript,html,Javascript,Html,我在使用JavaScript“严格模式”时遇到问题。我正在编写我的库构造函数,但是当我在库的开头启用strict模式时,“use strict”我收到此错误-未捕获类型错误:无法设置未定义的属性“e”。以下是我的构造函数代码:- (function(window, document, undefined){ "use strict"; function Ram(CSSselector) { //The main Constructor of the Library if (this =
“use strict”代码>我收到此错误-未捕获类型错误:无法设置未定义的属性“e”
。以下是我的构造函数代码:-
(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);
}
}
在非严格模式下,此
在方法外部指的是窗口
对象。严格模式消除了这种行为。由于您使用this
(作为全局this
)作为参数调用函数,因此会出现错误。因此,我应该如何设置这些属性而不破坏库的其余部分?首先,您需要更改最后一行,以使用窗口
,而不是this
。您的Ram
函数也需要通过new
关键字调用(将其作为普通函数调用不会创建此
对象供其使用)。最后,您应该看看闭包是如何编写的,因为您的代码没有完全遵循通常的模式。(您没有显示如何调用Ram
函数,但是从错误中我假设您将其作为一个普通函数调用)1:闭包通常是编写的(function(){})(
而不是(function(){}())
。2:是的,我是说那条线。和3:是的,如果你把它作为一个普通函数调用,你会得到这个错误。这不是JavaScript的工作方式(在非严格模式下,您的代码工作,但只是以一种不完整的方式;它将在窗口中设置对象,而不是您实际打算在其中设置的任何对象)。这里是Mozilla对象的概述,我建议您阅读本节: