简体   繁体   English

未捕获的TypeError:无法读取未定义的属性foo

[英]Uncaught TypeError: Cannot read property foo of undefined

My JavaScript: 我的JavaScript:

todo.completed = !todo.completed;

ERROR: 错误:

Uncaught TypeError: Cannot read property 'completed' of undefined
    at Object.toggleCompleted (script.js:34)
    at Object.toggleCompleted (script.js:89)
    at HTMLButtonElement.onclick ((index):33)
toggleCompleted @ script.js:34
toggleCompleted @ script.js:89
onclick @ (index):33

Am I missing something here? 我在这里想念什么吗?

It looks like you haven't declared the variable todo yet. 似乎您尚未声明变量todo。 Try something like todo = {}; 尝试类似todo = {}; Let me know if you have questions! 如果您有任何问题,请告诉我!

The variable todo has passed out of scope . 变量todo已超出范围 It's probably declared in a function that is outside the closure of handlers.toggleCompleted() when it is called. 可能是在调用handlers.toggleCompleted()闭包之外的函数中声明的。

There are a couple of ways to fix this, but as the simplest you can just make todo global: 有两种方法可以解决此问题,但最简单的方法就是将todo设为全局:

  1. Find var todo and remove var from the start. 找到var todo并从头开始删除var
  2. At the top of your JS add var todo = {}; 在您的JS顶部添加var todo = {};

This will make todo a global object that's always defined on your page. 这将使todo成为始终在页面上定义的全局对象。

What's so confusing about it is that the code will work in Plunkr, glitch or codepen, but not a text editor and browser, because of the way those sites's routing is set up. 令人困惑的是,由于这些站点的路由设置方式,因此代码可以在Plunkr,小故障或Codepen中运行,但不能在文本编辑器和浏览器中运行。 In your index.html file you need to replace <script src = "filename.js></script> with <script src="entire path to filename.js"></script> 在index.html文件中,您需要将<script src = "filename.js></script>替换为<script src="entire path to filename.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的类型错误:无法读取未定义的属性“foo” - Uncaught TypeError: Cannot read property 'foo' of undefined 未捕获的TypeError:无法读取未定义的属性“未定义” - Uncaught TypeError: Cannot read property 'undefined' of undefined 未捕获的TypeError:无法读取未定义的属性“数量” - Uncaught TypeError: Cannot read property 'quantity' of undefined 未捕获的TypeError:无法读取未定义的属性&#39;fromJSON&#39; - Uncaught TypeError: Cannot read property 'fromJSON' of undefined 未捕获的TypeError:无法读取未定义的属性“ timing” - Uncaught TypeError: Cannot read property 'timing' of undefined 未捕获的TypeError:无法读取未定义的属性&#39;formatter&#39; - Uncaught TypeError: Cannot read property 'formatter' of undefined Uncaught TypeError:无法读取未定义的属性“ stopVideo” - Uncaught TypeError: Cannot read property 'stopVideo' of undefined 未捕获的类型错误:无法读取未定义的属性“setCrossOrigin” - Uncaught TypeError: Cannot read property 'setCrossOrigin' of undefined 未捕获的TypeError:无法读取未定义的属性&#39;NaN&#39; - Uncaught TypeError: Cannot read property 'NaN' of undefined 未捕获的TypeError:无法读取未定义的属性&#39;getAttribute&#39; - Uncaught TypeError: Cannot read property 'getAttribute' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM