<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>INHERTIED</title>
<script charset="utf-8" type="text/javascript">
/*
* 原型继承的特点:
* 即继承了父类的模版 又继承了父类的原型对象
*/
function Person(name,age) {
this.name = name;
this.age = age;
}
//父类的原型对象属性
Person.prototype.id = 10;
function Son(sex) {
this.sex = sex;
}
Son.prototype = new Person('Tom',22);
var s = new Son('M');
document.write(s.name + ', ' + s.age + ', ' + s.sex + ', ' + s.id + '<br>');
/*
*类继承
*只继承类模版,不继承原型对象(借用构造函数的方式继承)
*/
function Father(name,age) {
this.name = name;
this.age = age;
}
Father.prototype.id = 'No1234';
function Boy(name,age,sex) {
Person.call(this,name,age);
this.sex = sex;
}
var b = new Boy('z3',23,'W');
document.write(b.name + ', ' + b.age + ', ' + b.sex + ', ' + b.id + '<br>');
/*
*混合继承 = 原型对象 + 借用构造函数继承
*/
function BasedClass(name,age) {
this.name = name;
this.age = age;
}
//父类的原型对象属性
BasedClass.prototype.id = 'No12345';
BasedClass.prototype.sayHi = function () {
document.write('Hi' + '<br>');
}
function InheritedClass(name,age,sex) {
BasedClass.call(this,name,age); //借用构造函数继承
this.sex = sex;
}
//原型继承
//只剩下 父类的实例 和 父类的原型对象的关系
InheritedClass.prototype = new BasedClass(); //继承父类的原型对象
var inh = new InheritedClass('w5',25,'W');
document.write(inh.name + ', ' + inh.age + ', ' + inh.sex + ', ' + inh.id + '<br>');
inh.sayHi();
</script>
</head>
<body>
</body>
</html>
结果: