重学es5构造函数 类与继承

ES6+已经在前端市场流行很多年了,似乎都快忘了以前常用的es5的一些特性,今天回顾一些es5的构造函数。

我现在有个需要,使用es5申明一个Person类,该类的方法有获取个人信息(getUserInfo)和工作(work),并实现继承:

  1. 分析:
  • 首先定义一个function Person() {},(定义类通常用大写字母开头)在这个Person类上有getUserInfowork两个方法;
  • 该Person类是否需要接收参数;
  • 如果在es5中实现继承,有构造函数继承和原型链继承,以及以上同时两种都继承;
  • 构造函数继:如果不需要接收参数,且Person原型链并没有方法,此时只需要继承构造函数继即可;
  • 原型链继承:如果不需要接收参数,且Person原型链并有方法,此时需要继承构造函数和原型链;
  • 如果需要接收参数,且构造函数和原型链都有方法,则需要继承构造函承和原型链;
  1. 声明一个Person类:
    function Person() {
        this.name = '小熊';
        this.age = 18;
        // 获取个人信息(构造函数方法)
        this.getUserInfo = function() {
            console.log(this.name + ' is ' + this.age + ' years old.');
        }
    }
  1. 实现构造函数继:
    function Student() {
        Person.call(this);
    }

    var s = new Student('小熊', 18);
    s.getUserInfo();

执行s.getUserInfo();会打印小熊 is 18 years old.
构造函数继承已完成;

  1. 在Person类原型链上新增一个work方法:
    Person.prototype.work = function () {
        console.log(this.name + '\'s job is the front end.');
    }

此时如果用以上构造函数的方法执行work方法胡报错Uncaught TypeError: s.work is not a function,因为Student并没有继承Person的原型方法

  1. 原型链继承:
    function Student() {
    }

    Student.prototype = new Person();
    var s = new Student();

执行s.getUserInfo();打印小熊 is 18 years old.
执行s.work();打印小熊's job is the front end.
由此可见原型链继承即可继承Person类的构造函数方法也可继承Person类的原型方法。
6.如果我的Person类是一下这样:

    function Person(name, age) {
        this.name = name;
        this.age = age;
        // 获取个人信息(构造函数方法)
        this.getUserInfo = function() {
            console.log(this.name + ' is ' + this.age + ' years old.');
        }
    }
    Person.prototype.work = function () {
        console.log(this.name + '\'s job is the front end.');
    }

Student类继承Person类如下:

    function Student(name, age) {
    }

    Student.prototype = new Person('小熊', 18);

    var s = new Student();

执行s.getUserInfo();打印undefined is undefined years old.
执行s.work();打印undefined's job is the front end.
说此方法并不能接收到传入的参数;

  1. 终极解决方案:
    function Student(name, age) {
        Person.call(this, name, age)
    }
    Student.prototype = new Person();

    var s = new Student('小熊', 18);
    s.getUserInfo();
    s.work();

你若这样写就完美解决了,Person.call继承构造函数,Student.prototype = new Person继承原型链;

  1. 原型链继承我们还可以更直观的这样写:
Student.prototype = Person.prototype;
  1. 完整版demo代码:
    // 声明一个Person类
    function Person(name, age) {
        this.name = name;
        this.age = age;
        // 获取个人信息(构造函数方法)
        this.getUserInfo = function() {
            console.log(this.name + ' is ' + this.age + ' years old.');
        }
    }
    Person.prototype.work = function () {
        console.log(this.name + '\'s job is the front end.');
    }

    function Student(name, age) {
        Person.call(this, name, age)
    }
    Student.prototype = Person.prototype;

    var s = new Student('小熊', 18);
    s.getUserInfo(); // 小熊 is 18 years old.
    s.work(); // 小熊's job is the front end.

此文仅回顾es5的类与继承。

你可能感兴趣的:(重学es5构造函数 类与继承)