zoukankan      html  css  js  c++  java
  • 浅析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/

  • 相关阅读:
    jQuery中常用方法和jQuery思维导图
    jQuery
    JS-AJAX and jQuery-AJAX
    Linux系统里导入maven项目
    maven项目里的ssh框架整合
    spring框架的两大核心:IOC和AOP
    JAVA的抽象类和接口
    JAVA面向对象的三大特征
    JAVA---面向对象
    JAVA---方法
  • 原文地址:https://www.cnblogs.com/Aralic/p/4508905.html
Copyright © 2011-2022 走看看