zoukankan      html  css  js  c++  java
  • js继承

    在传统的基于Class的语言如Java、C++中,继承的本质是扩展一个已有的Class,并生成新的Subclass。

    由于这类语言严格区分类和实例,继承实际上是类型的扩展。但是,JavaScript由于采用原型继承,我们无法直接扩展一个Class,因为根本不存在Class这种类型。

    但是办法还是有的。我们先回顾Student构造函数:

    function Student(props) {
        this.name = props.name || 'Unnamed';
    }
    
    Student.prototype.hello = function () {
        alert('Hello, ' + this.name + '!');
    }

    // PrimaryStudent构造函数:
    function PrimaryStudent(props) {
        Student.call(this, props);
        this.grade = props.grade || 1;
    }
    
    // 空函数F:
    function F() {
    }
    
    // 把F的原型指向Student.prototype:
    F.prototype = Student.prototype;
    
    // 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype:
    PrimaryStudent.prototype = new F();
    
    // 把PrimaryStudent原型的构造函数修复为PrimaryStudent:
    PrimaryStudent.prototype.constructor = PrimaryStudent;
    
    // 继续在PrimaryStudent原型(就是new F()对象)上定义方法:
    PrimaryStudent.prototype.getGrade = function () {
        return this.grade;
    };
    
    // 创建xiaoming:
    var xiaoming = new PrimaryStudent({
        name: '小明',
        grade: 2
    });
    xiaoming.name; // '小明'
    xiaoming.grade; // 2
    
    // 验证原型:
    xiaoming.__proto__ === PrimaryStudent.prototype; // true
    xiaoming.__proto__.__proto__ === Student.prototype; // true
    
    // 验证继承关系:
    xiaoming instanceof PrimaryStudent; // true
    xiaoming instanceof Student; // true
    

    用一张图来表示新的原型链:

    js-proto-extend

    注意,函数F仅用于桥接,我们仅创建了一个new F()实例,而且,没有改变原有的Student定义的原型链。

    如果把继承这个动作用一个inherits()函数封装起来,还可以隐藏F的定义,并简化代码:

    function inherits(Child, Parent) {
        var F = function () {};
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        Child.prototype.constructor = Child;
    }
    

    这个inherits()函数可以复用:

    function Student(props) {
        this.name = props.name || 'Unnamed';
    }
    
    Student.prototype.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
    
    function PrimaryStudent(props) {
        Student.call(this, props);
        this.grade = props.grade || 1;
    }
    
    // 实现原型继承链:
    inherits(PrimaryStudent, Student);
    
    // 绑定其他方法到PrimaryStudent原型:
    PrimaryStudent.prototype.getGrade = function () {
        return this.grade;
    };
  • 相关阅读:
    如果看了此文你还不懂傅里叶变换,那就过来掐死我吧【完整版】
    如何向外行解释什么是内存溢出
    【转】21副GIF动图让你了解各种数学概念
    C++buider IDE补丁
    c++buider2010 中.dfm无法打开设计界面的解决方法
    【转】Eclipse 常用快捷键 (动画讲解)
    修身养性,打磨自己
    毕向东java基础课学习笔记5——类型转换
    毕向东java基础课学习笔记——DOS中多命令来回切换的技巧
    vb 本机与SQL远程服务器时间同步
  • 原文地址:https://www.cnblogs.com/dragonh/p/6290526.html
Copyright © 2011-2022 走看看