Es6 的类(class)

首先根据es5的类(原型对象)的基本点做参照。

序号 基本点 es5 >es6
1 实例属性(方法)
2 原型属性(方法) 或 公共属性(方法)
3 es5的私有变量 或 私有属性
4 静态方法和静态属性
5 set 和 get
6 protected
6 继承

ps: 私有属性和私有变量并非相等,私有属性可在类与类之间直接传递,Es6现在没有或再提议。

// es5的私有变量间接通过实例方法传递和修改
function Person() {
    var privateVariable = '私有变量';
    this.getPrivateVarivable = function () {
        return privateVariable;
    }
    this.setPrivateVarivable = function (val) {
        privateVariable = val;
    }
}

概过:Es6 没有protected,私有属性private没有,只有5点:

  1. 实例属性
  2. 公共
  3. 静态
  4. set 和 get
  5. 继承
class Parent  {
    constructor(name='baba'){
        // 实例属性
        this.name=name;
        // 实例方法
        this.fn = () => {
            // todo
        }
        // 初始化执行某方法
        this.someMethod();
    }
    // 公共方法
    someMethod () {
        // todo
    }
    // 静态方法
    static function () {
        // todo
    }
    get longName () {
        return `lc_${this.name}`;
    }
    set longName (val) {
        this.name = val;
    }
}
// 公共属性
Parent.prototype.type = 'super';
// 静态属性
Parent.name = 'fn parent';

const parent = new Parent();
parent.longName; // lc_baba
parent.longName = '666';
parent.longName; // 'lc_666'

class Child extends Parent {
    constructor(...args) {
        // super()一定要有,并在construtor内第一行的位置
        super(...args);
        // 执行父类某方法时,不同事执行子类继承过来的方法
        // super.someMethod();
        this.someMethod();
    }
    some () {
        // todo
    }
}

猜你喜欢

转载自www.cnblogs.com/liangcheng11/p/9195325.html