Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript继承分类及其作用-总结 #8

Open
law-chain-hot opened this issue Feb 26, 2020 · 2 comments
Open

JavaScript继承分类及其作用-总结 #8

law-chain-hot opened this issue Feb 26, 2020 · 2 comments
Labels

Comments

@law-chain-hot
Copy link
Owner

law-chain-hot commented Feb 26, 2020

JavaScript继承分类及其作用-总结

image

先上分类

分类见最下面

自己的理解(用的最多的几个)

  1. 原型链继承

    • 使用 SubType.prototype = new SuperType()
    • 缺点:多个instance时,一个修改,会影响其他instance修改
  2. 构造函数继承

    • 使用如下
    • 缺点:无法继承prototype
function  SubType(){
    //继承自SuperType
    SuperType.call(this);
}
  1. 组合继承 (原型 + 构造)

    • 使用:不用多说 上面2个都用
    • 缺点:几乎完美,但是 SubTypeprototype 里面有重复的属性,会被 SubTypeinstance 的属性覆盖掉
    • 结论:浪费了空间?
  2. 组合寄生继承

    • 缺点:完美,修复了合寄生的缺点,但是过程复杂点
    • 如何使用:
      • 第一步
        • 得到prototype: Object.creat 一个新的对象,此对象只继承 SuperTypeprototype
      • 第二步
        • 使SubType得以使用父代的prototype:将 SubTypeprototype 指向新的对象。此时,SubType的prototype没有重复的属性
      • 第三步
        • 使SubType得到父代instance的属性:SubType 内部使用构造函数继承,内部使用SubType.prototype = new SuperType(),得到父代实例的属性
      • 第四步
        • 收获成果,直接new个新的实例吧
  • 一句话总结与组合寄生的区别保证一个纯净(不含父元素实例的属性和方法)的subtype的prototype

下面是自己画的图 组合寄生继承

  • 仅供参考。理解这个东西,多亏了BYVoid大神画的原型链的图,所以,可视化是很重要啊

image

分类

BYvoid 大神的图

image

@Ugly-Naked-Guy
Copy link

nice blog

@law-chain-hot
Copy link
Owner Author

nice blog

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants