gpt4 book ai didi

JavaScript - 继承

转载 作者:行者123 更新时间:2023-12-02 18:04:34 28 4
gpt4 key购买 nike

我有2个类别:动物( parent )和狗(动物的“ child ”),当我创建一个 Animal 对象并尝试提醒该动物的名称时,我得到了 undefined ,而不是她的真名。为什么?(抱歉重复发帖)

function Animal(name, year){
alert(name);
this.name = name;
this.year = year;

this.age = function (){
var n = new Date().getFullYear();
return n - this.year;
};
}

function Dog(name, year, color, type) {
this.color = color;
this.type = type;
Animal.call(this, name, year);

//override method age of animal
this.age = function (){
var n = new Date().getFullYear();
return (n - this.year) * 7;
};

Dog.prototype.age();
}

Dog.prototype = new Animal();

(这个js类名为:JsClass.js)

在 HTML 中:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="JsClass.js"></script>

<script type="text/javascript">
var p1 = new Animal("rex",2008);
</script>
<title>Insert title here</title>
</head>
<body>
</body>
</html>

(使用 Eclipse)

谢谢!

最佳答案

function Animal(name , year){
alert(name);
this.name = name;
this.year=year;

this.age= function (){
var n= new Date().getFullYear();
return n-this.year;
};
}
function Dog(name , year , color , type) {
this.color=color;
this.type=type;
Animal.call(this, name,year);

//override method age of animal
this.age= function (){
var n= new Date().getFullYear();
return (n-this.year)*7;
};

Dog.prototype.age();
}

// you invoke Animal as constructor. but you did not pass any argument to it . so name any year will be undefined in Animal() so alert will show undefined
Dog.prototype = new Animal();

// here is the normal invoke so alert will show rex
var p1 = new Animal("rex",2008);

您的代码将调用 Animal 两次,第一次调用警报未定义,第二次调用警报 rex

关于JavaScript - 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20205735/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com