关于javascript:总结继承的一些笔记

9次阅读

共计 1341 个字符,预计需要花费 4 分钟才能阅读完成。

原型链继承

// 父 ==> 构造函数
    function Person(name,age){
        this.name = name
        this.age = age
        
    }
    
    Person.prototype.sayHello = function(){console.log('谈话...')
    }
    
    // 子 ==> 构造函数
    function Child(name,age){
        this.name = name
        this.age = age
    }
    
    // 扭转 Child 的原型对象,指向 Person 的公共属性,达到原型链的继承形式
    Child.prototype = new Person()   
    Child.prototype.constructor = Child
    
    let p = new.Child()
    
    p.sayHello()   // '谈话...'

组合继承

 // 父 ==> 构造函数
    function Person(name,age){
        this.name = name
        this.age = age
    }
    Person.prototype.sayHello = function(){console.log('谈话...')
    }
    
    // 子 ==> 构造函数
    function Child(name,age){Person.call(this,name,age) // 继承 Person 的公有属性
    }
    
    // 扭转 Child 的原型对象,指向 Person 的公共属性,达到原型链的继承形式
    Child.prototype = new Person() 
    Child.prototype.constructor = Child
    
    let c = new.Child('wc',18)
    
    p.name   // 'wc'

寄生组合继承

// 父 ==> 构造函数
    function Person(name,age){
        this.name = name
        this.age = age
    }
    Person.prototype.sayHello = function(){console.log('谈话...')
    }
    
    // 子 ==> 构造函数
    function Child(name,age){Person.call(this,name,age) // 继承 Person 的公有属性
    }
    
    // 创立一个空对象,将 Person 的原型的对象指向空对象,并将空对象的地址赋值给 Child 的原型对象
    Child.prototype = Object.create(Person.prototype)
    Child.prototype.constructor = Child
    
    let c = new.Child('wc',18)
    
    p.name   // 'wc'

Es6 class 继承

class Person{constructor(name,age){
            // 公有属性
            this.name = name
            this.age = age
        }
        //sayHello 是共有属性 是原型链上的属性
        sayHello(){console.log('谈话...')
        }
    }
    
    // 让 Child 类 继承 Person 类
    class Child extends Person{constructor(name,age){super(name,age)  // 调用父类的 constrctor
        }
    }
    
    let c = new Child('wc',18)
    
    console.log(c.name) // 'wc'
    console.log(c.age) // 18
    c.ayHello() // '谈话了'

正文完
 0