<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function extend(sub,sup){
//实现只继承父类的原型对象
//1.用一个空函数进行中转
var F = new Function();
//2.实现空函数的原型对象和超类的原型对象转换
F.prototype = sup.prototype;
//3.原型继承
sup.prototype = new F();
//4.还原子类的构造器
sub.prototype.constructor = sub;
//5.保存一下父类的原型对象,一方面方便解耦,另一方面方便获取父类的原型对象,实现方法重载
sub.superClass = sup.prototype; //自定义一个子类的静态属性,接收父类的原型对象
//6.判断父类原型对象的构造器
if(sup.prototype.constructor == Object.prototype.constructor){
sup.prototype.constructor = sup; //手动还原父类对象的构造器
}
}
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person, //还原构造器,这里其实可以不用还原,因为在extend方法中已经实现了
sayHello: function(){
alert('hello world!');
}
}
function Boy(name,age,sex){
//绑定父类函数模版,实现构造函数继承,只复制了父类的模版
Boy.superClass.constructor.call(this,name,age);
this.sex = sex;
}
extend(Boy,Person);
//给子类添加一个原型对象方法
Boy.prototype.sayHello = function(){
alert('hello,javascript');
}
Boy.superClass.sayHello.call(b); //实现方法重载,调用父类的方法
var b = new Boy('z3',20,'nan');
alert(b.name);
alert(b.sex);
b.sayHello(); //调用子类重载的方法
</script>
</body>
</html>