我正在学习如何制作 Javascript 插件来显示模态窗口。 I'm trying to learn using this codepen .当我尝试在其他地方对其进行测试时,页面加载时出现以下错误:
Uncaught TypeError: Cannot set property 'raModal' of undefined
at raDialog.js:5 at raDialog.js:158
查看第 5 行,我可以看到错误是指将构建我要显示的模态的函数的开始,但我不太明白为什么会抛出错误在那条线上。
"use strict";
(function() {
// Make the constructor
this.raModal = function(){ //Line 5, error occurs here.
// Create global element references
this.closeButton = null;
this.modal = null;
this.overlay = null;
// Define option defaults
var defaults = {
autoOpen: false,
className: "",
closeButton: true,
content: "",
maxWidth: 500,
minWidth: 280,
minHeight: 150,
maxHeight: 700,
overlay: true,
onOK: "",
onClose: ""
};
// Create options by extending defaults with the passed in arugments
if (arguments[0] && typeof arguments[0] === "object") {
this.options = extendDefaults(defaults, arguments[0]);
}
if(this.options.autoOpen === true){
this.open();
}
};
//More code...
}()); //Line 158 also produces an error, might be related to Line 5's error.
我能够在 JSFiddle 中重现错误。 Link to JSFiddle
欢迎解释为什么会发生此错误。
最佳答案
在 strict
环境中,function
中的 this
将是 undefined
。
对于浏览器中的全局对象,使用window
。
'use strict';
(function () {
console.log(this);
window.foo = 'bar';
console.log(window.foo);
}());
或者你可以使用new
关键字:
'use strict';
(new function () {
this.foo = 'bar';
console.log(this.foo);
}());
参见 What does "use strict" do in JavaScript, and what is the reasoning behind it?获取更多信息。
关于Javascript 在页面加载时抛出 "Uncaught TypeError: Cannot set property ' x' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944164/