js继承再解析

之前学习过一段时间js继承,当时以为懂了(其实没懂),现在拿出来在回味复习一下~

参考了这篇文章: http://www.cnblogs.com/ayqy/p/4471638.html

js的继承 一共六种方式,可以参考【js高程三】

本文直接 用图描述了一遍 四.寄生组合继承(最佳方式)

function beget(obj){   // 生孩子函数 beget:龙beget龙,凤beget凤。
    var F = function(){};
    F.prototype = obj;
    return new F();
}
function Super(){
    // 只在此处声明基本属性和引用属性
    this.val = 1;
    this.arr = [1];
}
//  在此处声明函数
Super.prototype.fun1 = function(){};
Super.prototype.fun2 = function(){};
//Super.prototype.fun3...
function Sub(){
    Super.call(this);   // 核心
    // ...
}
console.log(Super.prototype)
var proto = beget(Super.prototype); // 核心
var proto2 = Super.prototype; // 核心
proto.constructor = Sub;            // 核心
Sub.prototype = proto;              // 核心

console.log(Super.prototype)

var sub = new Sub();
console.log(sub);
console.log(Sub);

其中有一个问题 Sub要继承Super为什么要通过一个F呢?

我们直接让 Sub 的 prototype = Super 的 prototype 会有什么影响?

原因有两点

  • 我们如果要向Sub 的 prototype 上添加新函数时候 如果按照刚才的假设*(Sub 的 prototype = Super 的 prototype) 那这个函数会添加到Super.prototype上,

  • 关于constructror 如果按照刚才的假设(Sub 的 prototype = Super 的 prototype) proto其实指向的是 Super,而不是我们希望的 Sub

posted @ 2017-08-24 14:29  _白马非马  阅读(179)  评论(0编辑  收藏  举报