class类对象模板ES6的语法糖

在传统的写对象模板的方式是这样的

function oldModel(){
    constructor(){
        this.name = '';
    }
}

oldModel.prototype.method=function(){

}

而ES6的class语法糖

class newModel {
    constructor(){
        this.name='';
    }
    method(){

    }
}

整体使用上更简约,代码量也更少。

在class内部,还有static的静态方法,查找资料和学习了下

类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。

class StaticMethodCall {
    constructor(){
        this.name1='1111';
    }
    static staticMethod() {
        return 'Static method has been called';
    }
    static anotherStaticMethod() {
        // 静态方法调用同一个类中的其他静态方法,可使用this关键字
        return this.staticMethod() + ' from another static method';
    }
    method(){
        return 'method';
    }
}
console.log(StaticMethodCall.staticMethod());
// 'Static method has been called'
 
console.log(StaticMethodCall.anotherStaticMethod());
// 'Static method has been called from another static method


var s = new StaticMethodCall();
s.staticMethod() // 报错,s.staticMethod is not a function
s.method() // 'method'

从类的构造函数里使用,需要类名来调用或者用类构造函数的属性来调用该方法

class StaticMethodCall {
    constructor() {
        console.log(StaticMethodCall.staticMethod());
        // 'static method has been called.'
        console.log(this.constructor.staticMethod());
        // 'static method has been called.'
    }
    static staticMethod() {
        return 'static method has been called.';
    }
}

 

资料采摘:https://blog.csdn.net/qq_38045106/article/details/84666638

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值