ES5 中 JavaScript的继承

来源:互联网 发布:vscode react 插件 编辑:程序博客网 时间:2024/05/17 07:33

在ES5 中,js 的继承主要分为以下几类:

  1. 类式继承
function fFatherClass(){};fFatherClass.prototype.fAlert = function{    alert(hello,i'am father class);    }function fChildClass(){};fChildClass.prototype = new fFatherClass();fChildClass.prototype.fChildOwnFunc = function(){//code}//因为是引用原型链的,所以缺点是一个子类修改了父类的方法或属性,那么对其它子类也会产生影响
  1. 构造函数继承
function fFatherClass(){    this.name = 'fatherClass';};fFatherClass.prototype.fAlert = function{    alert(hello,i'am father class);}function fChildClass(){    fFatherClass.call(this);}//但是这样继承有一个缺点,就是只能继承父类在构造函数中的方法与属性,不能继承原型链上的方法与属性
  1. 组合继承
function fFatherClass(){    this.name = 'fatherClass';};fFatherClass.prototype.fAlert = function{    alert(hello,i'am father class);}function fChildClass(){    fFatherClass.call(this);}fChildClass.prototype = new fFatherClass();
  1. 原型式继承
var oFather = {    //function    //var}var oChild = inheritObject(oFather);//然后就可以给子类添加自己的方法与属性了
  1. 寄生式继承
var oFather = {    //function    //var }var createChild(oFather){    var o = inheritObject(oFather);    o.childOwnFunc = function(){}    return o;}
  1. 寄生组合式继承
function oFatherClass(){    //var}oFatherClass.prototype.oFatherPrototypeFunction = function(){};function oChildClass(){    oFatherClass.call(this);    this.childVar = value;}inheritPrototype(oChildClass,oFatherClass);oChildClass.prototype.childOwnChildFunction = function(){};