天天看点

浅析5种Javascript继承关系的应用

在Javascript中如何实现继承关系的应用?Javascript继承概念:js是基于对象的,他没有类的概念,所以实现继承,需要使用js的原型prototype机制或者用applay和call方法实现。

1、原型链继承:

即子类通过prototype将所有在父类中通过prototype追加的属性和方法都追加到Child,从而实现了继承

为了让子类继承父类的属性(也包括方法),首先需要定义一个构造函数。然后,将父类的新实例赋值给构造函数的原型。

function parent(){                this.name="garuda";              }              function child(){                this.sex="man"              }              child.prototype=new parent();//核心:子类继承父类,通过原型形成链条              var test=new child();              console.log(test.name);              console.log(test.sex);
           

备注:在js中,被继承的函数称为超类型(父类、基类),继承的函数称为子类型(子类、派生类)。

使用原型继承存在两个问题:一是面量重写原型会中断关系,使用引用类型的原型,二是子类型还无法给超类型传递参数

2、借用构造函数继承

function parent(){                this.name="garuda";              }              function child(){                parent.call(this);//核心:借父类型构造函数增强子类型(传参)              }              var test =new parent();              console.log(test.name);
           

call方法是Function类中的方法

call方法的第一个参数的值赋值给类(即方法)中出现的this

call方法的第二个参数开始依次赋值给类(即方法)所接受的参数

4、apply()方法方式

apply方法接受2个参数,

A、第一个参数与call方法的第一个参数一样,即赋值给类(即方法)中出现的this

B、第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数

function Parent(username){                  this.username = username;                  this.hello = function(){                    alert(this.username);                  }                }                function Child(username,password){                  Parent.apply(this,new Array(username));                  this.password = password;                  this.world = function(){                    alert(this.password);                  }                }                var parent = new Parent("zhangsan");                var child = new Child("lisi","123456");                parent.hello();                child.hello();              child.world();
           

5、组合继承(原型链和构造函数组合)

function parent(){                this.name="garuda";              }              function borther(){                return this.name;              }              function child(){                parent.call(this)              }              child.prototype=new parent();              var test=new parent();              console.log(test.borther())
           

继续阅读