构造函数给出错误

时间:2017-11-29 06:37:44

标签: javascript html function constructor

我试图提供一个构造函数的例子。我希望我做得很好,仍然会出错。有人可以帮我吗?

<html>
<head></head>
<body> 
<script>

var alhpa = function(name, age){
this.name = name;
this.age = age; 
}

var obj1 = new alpha("Peter", 29);
var obj2 = new alpha("Jenny", 17);
var obj3 = new alpha("Mark", 34);

console.log(obj1);
console.log(obj2);
console.log(obj3);

</script> 
</body> 
</html> 

3 个答案:

答案 0 :(得分:3)

看起来你有拼写错误。

这应该是alpha not alhpa

var alpha = function(name, age){
    this.name = name;
    this.age = age; 
}

var obj1 = new alpha("Peter", 29);
var obj2 = new alpha("Jenny", 17);
var obj3 = new alpha("Mark", 34);

console.log(obj1);
console.log(obj2);
console.log(obj3);

答案 1 :(得分:1)

你犯了拼写错误 alhpa!= alpha

<强>演示

&#13;
&#13;
<html>
<head></head>
<body> 
<script>

var alpha = function(name, age){
this.name = name;
this.age = age; 
}

var obj1 = new alpha("Peter", 29);
var obj2 = new alpha("Jenny", 17);
var obj3 = new alpha("Mark", 34);

console.log(obj1);
console.log(obj2);
console.log(obj3);

</script> 
</body> 
</html> 
&#13;
&#13;
&#13;

答案 2 :(得分:1)

alhpa重命名为alpha。这是一个粗心的错误。

&#13;
&#13;
<html>
<head></head>
<body> 
<script>

var alpha= function(name, age){
this.name = name;
this.age = age; 
}

var obj1 = new alpha("Peter", 29);
var obj2 = new alpha("Jenny", 17);
var obj3 = new alpha("Mark", 34);

console.log(obj1);
console.log(obj2);
console.log(obj3);

</script> 
</body> 
</html>
&#13;
&#13;
&#13;