zoukankan      html  css  js  c++  java
  • JavaScript全面学习(继承)

    1.把原型(prototype)指向对象(继承)

    var Student = {
        name: 'Robot',
        height: 1.2,
        run: function () {
            console.log(this.name + ' is running...');
        }
    };
    
    var xiaoming = {
        name: '小明'
    };
    
    xiaoming.__proto__ = Student;   //仅用于演示目的。一般不要直接用obj.__proto__去改变一个对象的原型

    2.Object.create()方法可以传入一个原型对象,并创建一个基于该原型的新对象,但是新对象什么属性都没有

    // 原型对象:
    var Student = {
        name: 'Robot',
        height: 1.2,
        run: function () {
            console.log(this.name + ' is running...');
        }
    };
    
    function createStudent(name) {
        // 基于Student原型创建一个新对象:
        var s = Object.create(Student);
        // 初始化新对象:
        s.name = name;   // s的name属性赋值为新的name参数
        return s;
    }
    
    var xiaoming = createStudent('小明');
    xiaoming.run(); // 小明 is running...
    xiaoming.__proto__ === Student; // true

     3.当我们用obj.xxx访问一个对象的属性时,JavaScript引擎先在当前对象上查找该属性,如果没有找到,就到其原型对象上找,如果还没有找到,就一直上溯到Object.prototype对象,最后,如果还没有找到,就只能返回undefined

    arr ----> Array.prototype ----> Object.prototype ----> null  //数组的原型链
    foo ----> Function.prototype ----> Object.prototype ----> null //函数的原型链

    如果原型链很长,那么访问一个对象的属性就会因为花更多的时间查找而变得更慢,因此要注意不要把原型链搞得太长。

    4.定义一个构造函数并调用:

    function Student(name) {
        this.name = name;
        this.hello = function () {
            alert('Hello, ' + this.name + '!');
        }
    }
    var xiaoming = new Student('小明');
    xiaoming.name; // '小明'
    xiaoming.hello(); // Hello, 小明!

    注意,如果不写new,这就是一个普通函数,它返回undefined。但是,如果写了new,它就变成了一个构造函数,它绑定的this指向新创建的对象,并默认返回this,也就是说,不需要在最后写return this;

    为了区分普通函数和构造函数,按照约定,构造函数首字母应当大写,而普通函数首字母应当小写

    新创建的xiaoming的原型链是:

    xiaoming ----> Student.prototype ----> Object.prototype ----> null

    new Student()创建的对象还从原型上获得了一个constructor属性,它指向函数Student本身:

    //xiaoming.constructor 和 Student.prototype.constructor 和 Student这三个相等
    xiaoming.constructor === Student.prototype.constructor; // true
    Student.prototype.constructor === Student; // true
    
    Object.getPrototypeOf(xiaoming) === Student.prototype; // true
    
    xiaoming instanceof Student; // true

    红色箭头是原型链。Student.prototype指向的对象就是xiaomingxiaohong的原型对象,这个原型对象自己还有个属性constructor,指向Student函数本身。

    xiaomingxiaohong各自的hello是一个函数,但它们是两个不同的函数,虽然函数名称和代码都是相同的:

    xiaoming.name; // '小明'
    xiaohong.name; // '小红'
    xiaoming.hello; // function: Student.hello()
    xiaohong.hello; // function: Student.hello()
    xiaoming.hello === xiaohong.hello; // false

    为了节省内存,一般要把hello函数移动到xiaomingxiaohong这些对象共同的原型上,也就是Student.prototype:

    修改代码如下:

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

    5.还可以编写一个createStudent()函数,在内部封装所有的new操作(不需要用new调用):

    function Student(props) {
        this.name = props.name || '匿名'; // 默认值为'匿名'
        this.grade = props.grade || 1; // 默认值为1
    }
    
    Student.prototype.hello = function () {
        alert('Hello, ' + this.name + '!');
    };
    
    function createStudent(props) {
        return new Student(props || {})
    }
    var xiaoming = createStudent({
        name: '小明'
    });
    
    xiaoming.grade; // 1

    6.要想插入中间变量,把原型链修改为:

    new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null

    运用空函数F,代码如下:

    // PrimaryStudent构造函数:
    function PrimaryStudent(props) {
        // 调用Student构造函数,绑定this变量:
        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

    新的原型链:

    可以把继承这个动作用一个inherits()函数封装起来,简化代码:

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

    原代码修改如下:

    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;
    };

    7.可以用关键字class来定义类:

    class Student {                        //没有function关键字
        constructor(name) {
            this.name = name;
        }
    
        hello() {
            alert('Hello, ' + this.name + '!');
        }
    }
    //调用方法和以前一样:
    var xiaoming = new Student('小明'); xiaoming.hello();
    /*等效于上面的
    function Student(name) {
    this.name = name;
    }
    Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
    }
    */

    这样的话继承十分方便,可以直接用extends方法。不需要原型继承那么麻烦:

    class PrimaryStudent extends Student {
        constructor(name, grade) {
            super(name); // 记得用super调用父类的构造方法!否则父类的name属性无法正常初始化
            this.grade = grade;
        }
    
        myGrade() {
            alert('I am at grade ' + this.grade);
        }
    }

    这样,PrimaryStudent已经自动获得了父类Studenthello方法,我们又在子类中定义了新的myGrade方法。与原型继承的效果一样。

  • 相关阅读:
    【c++】重载操作符
    关于Repository模式
    UML建模系列文章总结
    windows批量创建用户
    数据库数据导入导出系列之五 C#实现动态生成Word(转)
    C#.bat文件清理工程目录
    ASP.NET用HttpListener实现文件断点续传
    LINQ to JavaScript
    依赖注入框架Autofac的简单使用
    spring boot日期转换
  • 原文地址:https://www.cnblogs.com/shen076/p/6178824.html
Copyright © 2011-2022 走看看