您的位置:首页 > Web前端 > JavaScript

js系列-4 继承

2016-02-26 14:55 591 查看
继承能达到代码的复用,js的继承不是基于类型的继承,而是基于原型的继承,也就是说直接从其他已有对象继承。

当一个函数对象被创建时,Function构造器产生的函数对象会运行类似这样的一些代码:

this.prototype={constructor:this}

这个prototype对象是存放继承特征的地方,因为这个对象在出现在实例的原型链上。

 

js不知道哪个函数对象会作为构造器,所以每个函数都有prototype属性。

1),对象冒充:

//对象冒充方式实现继承
functionParent(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}
functionChild(name,age){
//最重要的三行代码,先设一个引用指向一个函数,
//这个函数是父对象的构造方法,然后用引用调用这个函数
//这时候父对象的this已经变成子对象了,这样就将子对象的name赋值
//并且子对象也拥有了showName这个方法
//然后删除该引用
this.method =Parent;
this.method(name);
deletethis.method;

this.age=age;
this.showAge =function(){
alert(age);
}
}
varp = new Parent("zhang");
p.showName();
varc = new Child("li",12);
c.showName();
c.showAge();

2)c all方式实现继承:

      c all方法的使用,c all方法是Function对象中的方法,因此我们定义的每个函数都拥有该方法,可以通过函数名来调用c all方法,c all方法的第一个参数会被传递给函数中的this。从第二个参数开始,逐一赋值给函数中的参数。

function Hello(age,gender){
alert(this.name+" : "+age+" :"+gender);
}
var obj = new Object();
obj.name="zhang"
Hello.c all(obj,12,"M");
打印出来的是:zhang : 12 : M
//使用c all方法实现继承
function Parent(name){
this.name = name;
this.sayHello=function(){
alert(this.name);
}
}
function Child(name,password){
Parent.c all(this,name);
this.password= password;
this.sayWorld=function(){
alert(this.password);
}
}
var parent = newParent("zhang");
var child = newChild("lisi","123");
parent.sayHello();
child.sayHello();
child.sayWorld();

3)使用a pply方法实现继承:

     a pply也是Function对象的一个方法,他的使用方法与c all一样,只是第二个参数以后的参数是以数组形式呈现的。

//使用appl y方法实现继承
function Parent(name){
this.name = name;
this.sayHello=function(){
alert(this.name);
}
}
function Child(name,password){
Parent.app ly(this,[name]);
this.password= password;
this.sayWorld=function(){
alert(this.password);
}
}
var parent = newParent("zhang");
var child = newChild("lisi","123");
parent.sayHello();
child.sayHello();
child.sayWorld();

4)使用原型链的方式实现继承:   

//使用原型链方式实现继承
functionParent(){}
Parent.prototype.name="Hello";
Parent.prototype.sayHello=function(){
alert(this.name)
};
function Child(){}
Child.prototype=new Parent();
Child.prototype.password="world";
Child.prototype.sayWorld=function(){
alert(this.password)
};
var child = newChild();
child.sayHello();
child.sayWorld();

这种方式的缺点是无法实现参数传递

5)使用混合方式(原型+c all)实现继承(推荐)

//使用混合方式实现继承
function Parent(name){
this.name=name;
}
Parent.prototype.sayHello=function(){
alert(this.name)
};
function Child(name,password){
Parent.c all(this,name);
this.password=password;
}
Child.prototype=newParent();
//上面等于Child.prototype.__proto__ = Parent.prototype
Child.prototype.sayWorld=function(){
alert(this.password)
};
var child = newChild("zhang","123");
child.sayHello();
//1,child上找(找不到)2,child.__proto__(Child.prototype)上找(找不到)。3,Child.prototype.__proto__(Parent.prototype)上找(找到了)
child.sayWorld();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js