image.png

    借用构造函数

    1. function Wheel(style, wheelSize) {
    2. this.style = style
    3. this.wheelSize = wheelSize
    4. }
    5. function Sit(c, siteColor) {
    6. this.c = c
    7. this.siteColor = siteColor
    8. }
    9. function Car(name, style, wheelSize, c, siteColor) {
    10. this.name = name
    11. Wheel.call(this, style, wheelSize)
    12. Sit.call(this, c, siteColor)
    13. }
    14. var car = new Car('BMW', '花里胡哨', 100, '真皮', '红色')
    15. console.log(car)
    16. //Car {name: 'BMW', style: '花里胡哨', wheelSize: 100, c: '真皮', siteColor: '红色'}

    共享原型

    1. Father.prototype.name = 'xiaoming'
    2. function Father() {}
    3. function Son() {}
    4. function inherit(T, O) {
    5. T.prototype = O.prototype
    6. }
    7. inherit(Son, Father)
    8. console.log(new Son().name) //xiaoming
    9. //弊端 地址一样,改了Son,Father也变了
    10. Son.prototype.sex = 'male'
    11. var father = new Father()
    12. console.log(father.sex) //male

    圣杯模式

    1. Father.prototype.name = 'xiaoming'
    2. function Father() {}
    3. function Son() {}
    4. // function inherit(T, O) {
    5. // function F() {}
    6. // F.prototype = O.prototype
    7. // T.prototype = new F()
    8. // T.prototype.constuctor = T
    9. // T.prototype.uber = O.prototype
    10. // }
    11. var inherit = (function() {
    12. var F = function() {}
    13. return function(T, O) {
    14. F.prototype = O.prototype
    15. T.prototype = new F()
    16. T.prototype.constuctor = T
    17. T.prototype.uber = O.prototype
    18. }
    19. })()
    20. inherit(Son, Father)
    21. console.log(new Son().name) //xiaoming
    22. Son.prototype.sex = 'male'
    23. console.log(new Father().sex) //undefined

    Snipaste_2020-02-01_16-26-13.jpg

    Snipaste_2020-02-01_16-36-45.jpg

    ES5写法

    1. function Human(name){
    2. this.name = name
    3. }
    4. Human.prototype.run = function(){
    5. console.log("我叫"+this.name+",我在跑")
    6. return undefined
    7. }
    8. function Man(name){
    9. Human.call(this, name)
    10. this.gender = '男'
    11. }
    12. var f = function(){}
    13. f.prototype = Human.prototype
    14. Man.prototype = new f()
    15. Man.prototype.fight = function(){
    16. console.log('糊你熊脸')
    17. }

    ES6写法

    1. class Human{
    2. constructor(name){
    3. this.name = name
    4. }
    5. run(){
    6. console.log("我叫"+this.name+",我在跑")
    7. return undefined
    8. }
    9. }
    10. class Man extends Human{
    11. constructor(name){
    12. super(name)
    13. this.gender = '男'
    14. }
    15. fight(){
    16. console.log('糊你熊脸')
    17. }
    18. }