龙空技术网

列举javascript中三种继承结构和一个完美变种继承方式

糊薯干子茶 696

前言:

如今姐妹们对“js的继承方式有哪些”都比较着重,看官们都想要分析一些“js的继承方式有哪些”的相关知识。那么小编也在网摘上网罗了一些关于“js的继承方式有哪些””的相关资讯,希望大家能喜欢,朋友们快快来学习一下吧!

javascript继承关系

javascript种有三种继承方式

子对象继承父级的所有属性;

function Parent(){this.de="cms";}

Parent.prototype.ok=function(){console.log("yes!");}

var chlid=new Parent();

chlid.de//"cms"

chlid.ok()//"yes!"

子对象继承父构造函数的自身属性,不继承原型属性;

function chlid(){Parent.call(this);}

var a=new chlid();

a.ok()//a.ok is not a function

a.de//"cms"

子对象继承父构造函数原型属性,不继承父构造函数的自身属性。

function Parent(){this.de="cms";}

Parent.prototype.ok=function(){console.log("yes!");}

function chlid(){}

chlid.prototype=Parent.prototype;

var a=new chlid();

a.ok()//"yes!"

a.de//"undfined"

一个完美变种继承方式

这种方式可以使用第三方实现复杂的继承关系,虽然父级和子级没有直接的继承关系但是通过的第三方的原型链照样可以间接的访问父级的所有属性和方法,并且通过预留的后门也可以访问不属于原型链的属性和方法。

function Parent(){this.de="cms";}

Parent.prototype.ok=function(){return this.de;}

function chlid(){}

function inherit(C,P){

var F=function(){};

F.prototype=P.prototype;

C.prototype=new F();

C.uber=new P();

}

标签: #js的继承方式有哪些