ES6类与对象

1.ES5创建类

 function User(name, age) {
    this.name = name;
    this.age = age;
}
// 静态方法
User.getClassName = function () {
    return 'User';
}
User.prototype.changeName = function (name) {
    this.name = name;
}
User.prototype.changeAge = function (age) {
    this.age = age;
}
Object.defineProperty(User.prototype, 'info', {
    get() {
        return 'name:' + this.name + ' | age:' + this.age;
    }
});
/* var user = new User('lucky',30);
console.log(user.info); */
// 定义子类
function Manager(name,age,password) {
    User.call(this,name,age);
    this.password =password;    
}
// 继承静态方法
Manager.__proto__ = User;
// 继承prototype方法
Manager.prototype = User.prototype;
// 添加新方法
Manager.prototype.changePassword = function(password){
    this.password = password;
}

var m = new Manager('xxxx',30,'123');
console.log(m.name);
m.changeName('yyyy')
console.log(m.name);
console.log(m.info);

1.ES6创建类

'use strict'
class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    // 静态方法
    static getClassName() {
        return 'User';
    }
    changeName(name) {
        this.name = name;
    }
    // 定义属性info
    get info() {
        return 'name:' + this.name + ' | age:' + this.age;
    }
}
// 定义子类
class Manager extends User {
    constructor(name, age, password) {
        super(name, age);
        this.password = password;
    }
    changePassword(password) {
        this.password = password;
    }
    // 覆盖父类info
    get info() {
        let info = super.info;
        console.log(info);
        return 'new info ------';
    }
}
// let m = new Manager('baby',6,'123456');
// console.log(m.info);

// 对象没有提升
//let em = new Employee('eeee',11);//出错
class Employee extends User {
    // 默认自动加入constructor
    // constructor(...args){
    //     super(...args);
    // }

}
// let e = new Employee('zhangsan',20);
// console.log(e.info);

// 立即执行类"实例化"
// let customer = new class Customer {
//     constructor(name) {
//         this.name = name;
//     }
// }('lisi');
// console.log(customer);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ES6(ECMAScript2015)的出现,无疑给前端开发人员带来了新的惊喜,它包含了一些很棒的新特性,可以更加...
    cbw100阅读 15,519评论 3 233
  • 你可能已经听说过ECMAScript 6(简称 ES6)了。ES6 是 Javascript 的下一个版本,它有很...
    奋斗的小废鱼阅读 4,084评论 0 16
  • 你可能已经听说过ECMAScript 6(简称 ES6)了。ES6 是 Javascript 的下一个版本,它有很...
    米塔塔阅读 4,489评论 0 10
  • 面向对象的语言都有一个类的概念,通过类可以创建多个具有相同方法和属性的对象,ES6之前并没有类的概念,在ES6中引...
    Erric_Zhang阅读 4,816评论 1 4
  • 一、ES6简介 ​ 历时将近6年的时间来制定的新 ECMAScript 标准 ECMAScript 6(亦称 ...
    一岁一枯荣_阅读 11,272评论 8 25