<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>CREATE JAVASCRIPT OBJECTS USING OBJECT-LITERAL</h1>
<P id="text"></P>
<script language="javascript" type="text/javascript">
document.write("OBJECT CREATION");
function char(name, anime, specie){
this.name = name;
this.anime = anime;
this.specie = specie;
}
var character = char("Goku", "dragonballz", "saiyan");
document.getElementById("text").innerHTML = character.name + " is from " + character.anime + " and he is a super " + character.specie + " Alien ";
</script>
</body>
</html>所以..。正如您所看到的,我尝试使用javascript构造函数方法在控制台中创建一个对象,它没有显示,它说的是变量名未定义的字符。我目前正在学习javascript,所以我很想得到一些帮助。
发布于 2022-07-10 11:48:50
您需要添加new关键字来从构造函数创建对象实例。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>CREATE JAVASCRIPT OBJECTS USING OBJECT-LITERAL</h1>
<P id="text"></P>
<script language="javascript" type="text/javascript">
document.write("OBJECT CREATION");
function char(name, anime, specie){
this.name = name;
this.anime = anime;
this.specie = specie;
}
var character = new char("Goku", "dragonballz", "saiyan");
document.getElementById("text").innerHTML = character.name + " is from " + character.anime + " and he is a super " + character.specie + " Alien ";
</script>
</body>
</html>
为了更多的资源。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
https://stackoverflow.com/questions/72928227
复制相似问题