未捕获的类型错误:无法读取未定义的属性“说话”?
Posted
技术标签:
【中文标题】未捕获的类型错误:无法读取未定义的属性“说话”?【英文标题】:Uncaught TypeError: Cannot read property 'speak' of undefined? 【发布时间】:2021-04-23 01:38:43 【问题描述】:我是 javascript 的新手,我看不到问题,因为整个代码都是正确的。 必须出现在控制台中的预期输出是:
Hello Yaakov
Good Bye John
Good Bye Jen
Good Bye Jason
Hello Paul
Hello Frank
Hello Larry
Hello Paula
Hello Laura
Good Bye Jim
但它一直告诉我无法读取属性“说话”。
/* script.js*/
(function()
var helloSpeaker;
var byeSpeaker;
var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];
for (var i = 0; i < names.length; i++)
var firstLetter = names[i].charAt(0).toLowerCase();
if (firstLetter === 'j')
byeSpeaker.speak(names[i]);
else
helloSpeaker.speak(names[i]);
)();
/* speakhello.js*/
(function(window)
var helloSpeaker = new Object();
var speakWord = "hello"
helloSpeaker.speak = function(name)
console.log(speakWord + "" + name);
;
window.helloSpeaker = helloSpeaker;
)(window);
/*speakgoodbye.js*/
(function(window)
var byeSpeaker = new Object();
var speakWord = "Good Bye";
byeSpeaker.speak = function(name)
console.log(speakWord + "" + name);
;
window.byeSpeaker = byeSpeaker;
)(window);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module 4 Solution Starter</title>
<script src="SpeakHello.js"></script>
<script src="SpeakGoodBye.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Module 4 Solution Starter</h1>
</body>
</html>
【问题讨论】:
【参考方案1】:不要在script.js
中声明局部变量helloSpeaker
和byeSpeaker
。他们阻止访问在其他 JS 文件中分配的全局变量。
/* speakhello.js*/
(function(window)
var helloSpeaker = new Object();
var speakWord = "hello"
helloSpeaker.speak = function(name)
console.log(speakWord + "" + name);
;
window.helloSpeaker = helloSpeaker;
)(window);
/*speakgoodbye.js*/
(function(window)
var byeSpeaker = new Object();
var speakWord = "Good Bye";
byeSpeaker.speak = function(name)
console.log(speakWord + "" + name);
;
window.byeSpeaker = byeSpeaker;
)(window);
/* script.js*/
(function()
var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];
for (var i = 0; i < names.length; i++)
var firstLetter = names[i].charAt(0).toLowerCase();
if (firstLetter === 'j')
byeSpeaker.speak(names[i]);
else
helloSpeaker.speak(names[i]);
)();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module 4 Solution Starter</title>
<script src="SpeakHello.js"></script>
<script src="SpeakGoodBye.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Module 4 Solution Starter</h1>
</body>
</html>
【讨论】:
以上是关于未捕获的类型错误:无法读取未定义的属性“说话”?的主要内容,如果未能解决你的问题,请参考以下文章
未捕获的类型错误:无法读取未定义的属性 toLowerCase
错误:`未捕获(承诺中)类型错误:无法读取未定义的属性'doc'`
JQuery:未捕获的类型错误:无法读取未定义的属性“调用”
NextJS:未捕获的类型错误:无法读取未定义的属性(读取“属性”)