• 浅析js中的继承


    在js中继承主要是依靠原形链来实现。如果不了解原型相关知识,建议读者先去了解原形链。

    每个构造函数都有一个原型对象(prototype),原型对象都包含一个指向构造函数的指针(constructor),而实例都包含一个指向原型对象的内部指针成为隐式原型(__proto__)。

    组合继承

    
    //父类
    function Parent() {
        this.name = 'parent';
    }
    
    Parent.prototype.getName = function() {
        console.log(this.name);
    }
    
    //子类
    function Child() {
        //继承父类的属性
        Parent.call(this);          //第二次调用Parent()
    }
    
    //子类的原型 指向父类的实例对象
    Child.prototype = new Parent(); //第一次调用Parent()
    //修正子类的constructor指向
    Child.prototype.constructor = Child;
    
    

    原型继承

    
    //父类
    var parent = {
        name: 'parent'
        getName: function() {
            console.log(this.name);
        }
    };
    
    //代理中介
    function object(o) {
        var F = function(){};
        F.prototype = o;
        return new F();
    }
    
    //子类
    var child = object(parent);
    
    

    寄生式组合继承

    结合第一、二中方法,我们实现了更高校的第三种寄生组合式继承。

    
    //父类
    function Parent() {
        this.name = 'parent';
    }
    
    Parent.prototype.getName = function() {
        console.log(this.name);
    }
    
    
    //代理中介
    function object(o) {
        var F = function(){};
        F.prototype = o;
        return new F();
    }
    
    //子类原型 继承父类的原型 
    function inhertPrototype(Parent, Child) {
        var prototype = obj(Parent.prototype);
        prototype.constructor = Child;
        Child.prototype = prototype;
    }
    
    //子类
    function Child() {
        //继承父类的属性
        Parent.call(this);  
    }
    
    //子类继承父类
    inhertPrototype(Parent, Child);
    
    

    关注我的微博:http://weibo.com/u/3059735367
    关注我的github博客:http://aralic.github.io/

  • 相关阅读:
    Secure your iPhone with 6 digit passcode by upgrading to iOS9
    Threatening letter in Naver Line App
    Android Malware Analysis
    OGG目录清理数据
    RAC配置2个私网网卡使用HAIP服务
    sql调优脚本
    匿名内部类
    权限修饰符
    Android源码目录结构
    luffy项目:基于vue与drf前后台分离项目(1)
  • 原文地址:https://www.cnblogs.com/Aralic/p/4508905.html
Copyright © 2020-2023  润新知