[英]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.