javascript——混合继承(借用构造函数+原型继承)

时间:2021-10-11 17:52:57
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="UTF-8">
/**
* 借用构造函数继承:缺点是无法继承父类原型中的
*/

function Parent(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}

Parent.prototype.id = 10;

function Child(name,age,sex){
Parent.call(this,name,age,sex);
this.sayName = function(){
alert('我是'+name);
};
}

var c1 = new Child('leo',23,'男');
alert(c1.name);
alert(c1.age);
alert(c1.sex);
c1.sayName();

/**
* 原型继承 + 借用构造函数继承 = 混合继承
*/
Child.prototype = new Parent();
var c2 = new Child('liuao',22,'男');
alert(c2.id);//10

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