美文网首页
面向对象

面向对象

作者: 萌琦琦de诗扬 | 来源:发表于2018-09-06 15:09 被阅读0次

    实现继承的方式

    1. 原型继承

    子构造函数.prototype = 父实例 (Child.prototype = new Father();)

    function Father(){
        this.a = [1, 2, 3]
    }
    Father.prototype.aFun = function(){
        console.log('a')
    }
    
    function Child() {
        this.name = 'bb'
    }
    Child.prototype = new Father();
    Child.prototype.bFun = function() {
        conosle.log('b')
    }
    
    var child1 = new Child();
    child1.aFun();  //a
    child1.a;
    

    缺点:

    • 定义在父构造函数内的属性,每个父实例都会有各种的一份实例属性。子构造函数的原型是父构造函数的一个实例,每个子实例共享相同的原型上的属性。
    • 无法从子构造函数向父构造函数传递参数
    1. 构造函数继承
    function Father(name){
        this.a = [1, 2, 3];
        this.name = name;
    }
    
    function Child() {
        Father.call(this, 'qi')
        this.value = 'bb'
    }
    
    var child1 = new Child();
    

    缺点: 无法共享原型对象上的方法

    1. 通过构造函数继承属性,通过原型链继承方法(应用广泛)
    function Father(name){
        this.a = [1, 2, 3];
        this.name = name;
    }
    Father.prototype.aFun = function(){
        console.log('a')
    }
    
    function Child() {
        Father.call(this, 'qi')
        this.value = 'bb'
    }
    Child.prototype = new Father();
    Child.prototype.constructor = Child;
    Child.prototype.bFun = function() {
        conosle.log('b')
    }
    
    var child1 = new Child();
    

    相关文章

      网友评论

          本文标题:面向对象

          本文链接:https://www.haomeiwen.com/subject/kwsxgftx.html