天天看点

JS面向对象-面向对象编程 - 封装

何为面向对象编程

封装

ES5示例

let People = function(name, age) {
    this.name = name;
    this.age = age;

    this.introduceMyself = function() {
        console.log(`Hi, my name is ${this.name}, age is ${this.age}`);
    }
}

let p = new People('zzh', 18);
p.introduceMyself(); // result: Hi, my name is zzh, age is 18      

ES6示例

class People {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    introduceMyself() {
        console.log(`Hi, my name is ${this.name}, age is ${this.age}`);
    };
}

let p = new People('zzh', 18);
p.introduceMyself(); // result: Hi, my name is zzh, age is 18      

继续阅读