Javascript 在页面加载时抛出 "Uncaught TypeError: Cannot set property ' x' of undefined"

标签 javascript jquery html

我正在学习如何制作 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/

相关文章:

javascript - 丢失的 ;声明之前?

html - 尝试将整个 <Figure> 元素作为页面中的链接时,在 W3C 标记验证中出现错误

html - Bootstrap 3 字形 CDN

javascript - 如何通过javascript函数的返回值生成href链接的内容?

javascript - 每次表更改时执行 JavaScript 代码

javascript - jQuery 用元素数组为each() 播种

html - 全高分区

javascript - 为什么 typeof undefined 是返回字符串?

javascript - 如何直接从服务器端过滤的存储中获取值

jquery - 如何使用 jQuery 获取下拉列表中所选值的计数