未捕获的typeError无法读取未定义的属性

uncaught typeError can not read property of undefined

本文关键字:读取 未定义 属性 typeError      更新时间:2023-09-26

我有两个javascript。一个是用于读取图像文件,我称之为"register.js"

var FileUpload = (function (fileElement) {
  //code goes here other functions and stuff
  function fileread (event) {
    //code goes here
  }
  return {
    files: fileread // assign fileread as property and return
  };  
}(document.getElementById('up')))

我添加了另一个名为"call.js"的文件,当"onChange"事件发生时,它将使用FileUpload对象读取文件

function load () {
  console.log(FileUpload.files);
  document.getElementById('up').addEventListener('change', FileUpload.files,false);
}
window.onload=load;

但无论我在哪里运行代码,都会出现以下错误。如何修复此错误?

create:115未捕获的类型错误:无法读取的属性"files"未定义

我猜您已经忘记使用module.exportsrequire了。在register.js末尾添加:

module.exports = FileUpload;

call.js的开头添加:

var FileUpload = require('./register');

您需要将./register更改为register.js的目录。由于节点采用javascript文件,因此可以省略.js扩展名。

这就是问题所在:

return
      {
         files:fileread// assign fileread as property and return
      };  

Javascript中的分号是可选的,因此它不知道您是否要返回{files:fileread}。它认为return是一个语句,并且{files:fileread}则不同。

对此进行更改,一切都应该正常:

return {
    files:fileread// assign fileread as property and return
};