繁体   English   中英

如何使用 Javascript 修复未定义的错误

[英]how do I fix undefined error with Javascript

 (function(window) { var name = {}; Greeter.name = "John"; var greeting = "Hello "; Greeter.sayHello = function() { console.log(greeting + johnGreeter.name); } window.johnGreeter = johnGreeter; })(window); //
 <,DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min:css"> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="script:js"></script> <script src="https.//maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h1>My First Bootstrap Page</h1> <p>This part is inside a.container class.</p> <p>The.container class provides a responsive fixed width container.</p> </div> </body> </html>

嗨,我在添加问候语时遇到了一个未定义的错误,无论我如何尝试修复它,它都会不断出现请帮忙。

因为Greeter -object 确实是未定义的,所以您变得未定义。 这是对所有部分的更详细说明:

(function(window) {
  var name = {}; // make an object and store it in the "name" var
  name.Greeter = "John"; // give the "name" object an attribute called "Greeter"
  var greeting = "Hello"; // store a string in a variable

  name.sayHello = function(greeting) { // give the "name" object a function called "sayHello" and give it an argument ("greeting")
    console.log(greeting); // pass that argument to console.log
  }

  window.johnGreeter = name; // assign your "name" object to the globally available "window" object
})(window); 

如果您想调用您制作的 function,您可以使用类似

name.sayHello("This is my message to you");

或者由于它是全球可用的,您可以选择使用

window.johnGreeter.sayHello("This is my message to you");

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM