码迷,mamicode.com
首页 > 编程语言 > 详细

javascripe之继承

时间:2017-06-10 23:33:09      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:基于   另一个   构造函数   需要   cto   继承   his   封装   副本   

继承方法

原型链继承

继承是通过创建构造函数的实例实现的,孩子的prototype属性等于父亲构造函数的实例,这样孩子原型对象的prototype属性指向父亲的原型对象。由此原来存在于父亲的实例中的所有属性和方法,现在也存在于孩子的原型对象中了,这样就建立了继承关系。

借用构造函数

使用call()或apply()方法在将来新创建的对象上执行构造函数。

组合继承

原型链实现对原型属性和方法的继承,构造函数实现对实例属性的继承。

function parent(age,name){

this.age=age;

this.name=name;

}

parent.prototype.say =function(){

alert(this.name)

};

function child(age,name){

    //构造函数继承

parent.call(this.age,name);

}

//原型继承

var child.prototype=new parent(“LIli”,”13”);

child.prototype.constructor= child;

原型式继承

创建一个临时构造函数(obj),将传入的父亲对象(o)作为构造函数的原型,然后返回这个临时构造函数的一个新实例。孩子作为临时构造函数的实例,由此实现了给定父亲对象的浅复制,而复制得到的孩子副本可以实现进一步的改造。

var obj(o){

function F(){}

F.prototype=o;

return new F();

}

var parent = {name:”Li”};

var child = obj(parent);

Child.age=”23”;

 

寄生式继承

创建一个封装过程的函数,将原型式继承和增强对象的内容全部封装到函数中,通过调用封装函数实现继承。

function createChild(parent){

var tempChild = obj(parent);

tempChild.say = function(){

alert(this.name);

}

return tempChild

}

var child = creatChild(perent);

组合继承

是实现基于类型继承的最好方法。组合继承在每个孩子实现继承过程时都需要两次调用父亲超类型,一次是在孩子构造函数内部,另一个是创建孩子原型的时候。组合继承是将孩子在创建原型时进行封装,这样任何一个孩子只需要在创建构造函数时调用父亲构造函数。

function inherentPrototype (child,parent){

var prototype= new Obj(parent.prototype);

prototype.prototype = prototype;

child.constructor = prototype;

}

function parent(age,name){

this.age=age;

this.name=name;

}

parent.prototype.say =function(){

alert(this.name)

};

function child(age,name){

    //构造函数继承

parent.call(this.age,name);

}

//原型继承

inherentPrototype (child,parent);

javascripe之继承

标签:基于   另一个   构造函数   需要   cto   继承   his   封装   副本   

原文地址:http://www.cnblogs.com/microcosm/p/6980190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!