未捕获的类型错误:无法读取未定义的属性“说”?

时间:2021-01-18 18:12:13

标签: javascript html typeerror

我是 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

但它一直告诉我无法读取属性 'speak'。

/* 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 个答案:

答案 0 :(得分:0)

不要在 helloSpeaker 中声明局部变量 byeSpeakerscript.js。它们阻止访问在其他 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>