js中Es5与Es6的创建对象与继承

138 阅读1分钟

在JavaScript 语言中,生成实例对象的传统方法是通过构造函数,es6的class 的出现 基本上可以替代了es5的构造函数和原型,使之代码结构上更加简洁。

在用到class写法,可以更加直观的体验到对象编程。

这是es5的写法

    //父 --super--
    function Human(name, age) {
        this.name = name
        this.age = age
    }
    Human.prototype.habit = function () {
        console.log(this.name, this.age);
    }
    let stu = new Human('su', 22)
    console.log(stu);

这是es5的继承

    // 父级 --super--
    function Father(name, age) {
        this.name = name
        this.age = age
    }
    // 型
    Father.prototype.hi = function () {
        console.log(this.name + this.age);
    }

    // 子级
    function Son(name, age, gender) {
        // 我自己没有,我拿父级的
        Father.call(this, name, age)
        // call改变了指向,现在指向了Son↑
        this.gender = gender
    }
    // 型的赋予
    Son.prototype.hi = Father.prototype.hi
    let erzi = new Son('su', 18, '男')
    console.log(erzi);

接下来,让我们看一下es5与es6的写法有何不同

es6的写法

// class +名字
    class Human {
        // constructor(属性)
        constructor(name, age, gender) {
            this.name = name
            this.age = age
            this.gender = gender
        }
        // 方法直接写
        hi() {
            console.log(this.name, this.age, this.gender);
        }

    }
    let newObj = new Human('jack', 11, '男')
    console.log(newObj);

es6的继承

 // class +名字
    class Human {
        // constructor(属性)
        constructor(name, age, gender) {
            this.name = name
            this.age = age
            this.gender = gender
        }
        // 方法直接写
        hi() {
            console.log(this.name, this.age, this.gender);
        }
    }

    // Class 可以通过`extends`关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
    class student extends Human { }
    let newObj = new student('jack', 11, '男',)
    console.log(newObj);

其中es6的继承中的class student extends Human { }中的{}里面还可以写东西,可以让更多细节清晰,可以类比一下cs5的继承。

    class student extends Human {
        constructor(name, age, gender, adress) {
    // super类似于Human.call,改变了指向,真的和es5差不了多少,只是写法不一样
        super(name, age, gender)
        this.adress = adress
    }
     }
    let newObj = new student('jack', 11, '男','深圳')
    console.log(newObj);

两者以后根据情况使用,喜欢哪个用哪个~