javascript实现继承的五种方法

<script type="text/javascript">
// 第一种 对象传递实现
function Parent(name){
this.name = name;
this.say = function(){
alert(this.name);
}
}
function Child(name,age){
this.method = Parent; // 来自父类
this.method(name); // 传入新的参数
delete this.method;
this.age = age;
this.talk = function(){
alert(this.age);
}
}

var parent = new Parent("parent");
var child = new Child("child","20");
parent.say(); // 调用父类方法
child.say(); // 调用子类方法
child.talk(); // 调用子类新方法

// 第二种 call方式实现
function Parent(name){
this.name = name;
this.say = function(){
alert(this.name);
}
}
function Child(name,age){
Parent.call(this,name);//第一个参数为Child类中的this
this.age = age;
this.talk = function(){
alert(this.age);
}
}

var parent = new Parent("parent");
var child = new Child("child","20");
parent.say(); // 调用父类方法
child.say(); // 调用子类方法
child.talk(); // 调用子类新方法

// 第三种 apply方式实现
function Parent(name){
this.name = name;
this.say = function(){
alert(this.name);
}
}
function Child(name,age){
Parent.apply(this,new Array(name));//第一个参数为Child类中的this
this.age = age;
this.talk = function(){
alert(this.age);
}
}

var parent = new Parent("parent");
var child = new Child("child","20");
parent.say(); // 调用父类方法
child.say(); // 调用子类方法
child.talk(); // 调用子类新方法

// 第四种 原型继承
function Parent(){

}
Parent.prototype.name="parent";
Parent.prototype.say = function(){
alert(this.name);
}
function Child(){

}
Child.prototype = new Parent(); // 追加继承
Child.prototype.name = "child";
Child.prototype.age = 20;
Child.prototype.talk = function(){
alert(this.age);
}
var parent = new Parent();
var child = new Child();
parent.say(); // 调用父类方法
child.say(); // 调用子类方法
child.talk(); // 调用子类新方法

// 第五种 混合继承
function Parent(name){
this.name = name;
}
Parent.prototype.say = function(){
alert(this.name);
}

function Child(name,age){
Parent.call(this,name); // 将父类的属性继承过来
this.age = age;
}
Child.prototype = new Parent();// 先继承过来 在追加
Child.prototype.talk = function(){
alert(this.age);
}
var parent = new Parent("parent");
var child = new Child("child",20);
parent.say();
child.say()
child.talk();
</script>

posted @ 2016-02-17 13:58  一渡  阅读(77)  评论(0)    收藏  举报