javascript中通过prototype来继承其他对象,这样就是实现了扩充对象的属性和方法。
下面的代码,用person的prototype的属性来获取parent,把parent归为一个称为prototype的属性,让parent成为了person的一部分。
代码:
<html>
<head>
<title>prototype</title>
<meta charset="utf-8">
<script language="javascript" >
function parent(papa,mama)
{
this.papa = papa;
this.mama = mama;
}
function person(name,age)
{
this.name = name;
this.age = age;
this.show = showPerson;
function showPerson()
{
document.write("<br>姓名:"+ this.name);
document.write("<br>年龄:"+ this.age);
document.write("<br>爸爸:"+ this.papa);
document.write("<br>妈妈:"+ this.mama);
}
}
</script>
</head>
<body>
<script language="javascript">
person.prototype = new parent();
var p = new person("小喵咪",28);
//通过with关键字 直接引用属性
with(p)
{
papa = "大咪";
mama = "大喵";
}
p.show();
</script>
</body>
</html>