构造函数—es5与es6

//构造函数  构造器-----es5

function Animal(type, name, age, sex) {

    this.type = type;

    this.name = name;

    this.age = age;

    this.sex = sex;

}

//定义实例方法(原型方法)

Animal.prototype.print = function () {

    console.log(`【种类】:${this.type}`);

    console.log(`【名字】:${this.name}`);

    console.log(`【年龄】:${this.age}`);

    console.log(`【性别】:${this.sex}`);

}

const a = new Animal("狗", "旺财", 3, "男");

a.print();

for (const prop in a) {

    console.log(prop)//type  name age sex print

}


##传统的构造函数的问题

1. 属性和原型方法定义分离,降低了可读性

2. 原型成员可以被枚举

3. 默认情况下,构造函数仍然可以被当作普通函数使用



//es6 构造函数语法糖

class Animal {

    constructor(type, name, age, sex) {

        this.type = type;

        this.name = name;

        this.age = age;

        this.sex = sex;

    }

    print() {

        console.log(`【种类】:${this.type}`);

        console.log(`【名字】:${this.name}`);

        console.log(`【年龄】:${this.age}`);

        console.log(`【性别】:${this.sex}`);

    }

}

const a = new Animal("狗", "旺财", 3, "男");

a.print();

for (const prop in a) {

    console.log(prop);//type  name age sex

}

## 类的特点

1. 类声明不会被提升,与 let 和 const 一样,存在暂时性死区

2. 类中的所有代码均在严格模式下执行

3. 类的所有方法都是不可枚举的

4. 类的所有方法都无法被当作构造函数使用

5. 类的构造器必须使用 new 来调用

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容