ES6基本的语法(八) Class

ES6 Class

和 ES5 的对比和基本说明

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

const p = new Point(1, 2);

// 使用 class 之后

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
const p = new Point(1, 2);

上面的代码中定义了一个“类” 类名是 Pointconstructor 是它的方法体。所以 p.constructor === Point.prototype.constructor

Class 基本语法


class Point {
    toString() {
        ...
    }
    toValue() {
        ...
    }
    toKeys() {
        ...
    }

    // ES7 中的写法 ES6 不支持
    name = "ccc"
}

var const = new Point(1, 2);

// 等同于

Point.prototype = {
    toString(){},
    toValue(){},
    toKeys(){}
}

上面的 class 里面定义了一个 toString() 方法,在 Point 里面写的方法会直接写在原型上。在 ES6 在 class 里面直接赋值会报错,在 ES7 中不会。

静态方法

在前面加上 static 关键字,该方法不会被实例继承,只能使用。这种就叫静态方法

class Fun {
    // 在前面加上 static 关键字,该方法不会被实例继承,只能使用
    static name (){
        return 'MyFun';
    }
}

Fun.name(); // 'MyFun'

let fun = new Fun();
fun.name();
// TypeError: fun.name is not a function

上面的代码中,name 方法前有 static 关键字,表示 name 是一个静态方法,可以 Fun.name() 调用,而不是在 fun 调用。

继承和 super


class Fun {
    static name (){
        return 'MyFun';
    }
}

class Box extends Fun {

}

Box.name() // 'MyFun'

上面代码中,Fun 有一个静态方法,Box 继承 Fun 之后可以调用这个方法。

可以使用 super,调用父类的静态方法。


class Fun {
    static name (){
        return 'MyFun';
    }
}

class Box extends Fun {
    static name () {
        console.log(super.name() + ', ccc')
    }
}

Box.name() // 'MyFun,ccc'

ES7 Class 的新特性

  • static prop = xxx; 静态属性
  • property = xxx; 私有属性
  • @decortor 装饰器

静态属性和私有属性

我在上面文章说了,在 ES7 中可以直接 static prop = xxx 写静态属性,也可以 myName = 'ccc' 写私有属性


class Fun {
    static name = 'ccc'; // 静态属性
    constructor(){
        this.keyValue = ''
    }
    myName = 'ccc'; // 私有属性
    getCount(){
        console.log('发送请求')
    }
}

var fun = new Fun()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值