ES6基础-7

Posted webcyh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES6基础-7相关的知识,希望对你有一定的参考价值。

Class类

//类的使用
    var Example = class //匿名类
        constructor(age)
            this.age = age;
        
    
    var Example2 = class //命名类
        constructor(age)
            this.age = age;
        
    
    //类不可以重复声明 注意:类没有提升之说、必须在使用之前定义 类方法之间不能出现分号
    //ES6 当中还是可以使用prototype添加方法属性的,如下 覆盖或者初始化的时候添加
    Example.prototype.func = function()
            console.log("I can do it!");
        
    
    Object.assign(Example.prototype,
        Run()
            console.log("hello world!");
        
    );
    var test = new Example();
    test.Run();
    test.func();

技术图片

 

 静态属性

    //静态属性 在类内部只有静态方法
    var Example3 = class //匿名类
        static name = "webcyh";//注意这里是分号//这个是类的静态属性 通过类名.属性名访问 或者给所
        constructor(age)
            this.age = age;
        
    
    var Example4 = class //匿名类
        static name:"webcyh";//注意这里是分号//这个是类的静态属性 通过类名.属性名访问 或者给所
        constructor(age)
            this.age = age;
        
    
    //给所有的class添加静态属性
    class.prototype.he = "hehe";
    console.log(Example3.he);//这个访问的是所有class都具有的静态属性
    console.log(Example3.name);//当前这的类具有的属性

访问Exampl的name会返回声明类名的class后边的类名

 

实例方法以及类的实例创建

var Example4 = class //匿名类
        constructor(age)
            this.age = age;
            this.say = str=>console.log(`I fuck you $str`)//实例方法
        ;
        static func()
            console.log("hh");
        
    
    //给所有的class添加静态属性
    console.log(Example3.name);//当前这的类具有的属性
    Example4.func();
    //class的实例必须使用new
    var n4 = new Example4();
    n4.say("time");//执行实例方法

技术图片

 

 注意这里的与ES5的不同 该实例的原型prototype就是创建该对象的类 而不是该类的prototype 该对象.__proto__.num = function()相当于在该类添加方法

var n4 = new Example4();
    n4.say("time");//执行实例方法
    console.log(n4.__proto__);
    n4.__proto__.getNum = ()=>console.log("sdsdf");
    n4.getNum();
    var n3 = new Example4();
    n3.getNum();

技术图片

 

 decorator是一个函数,用于修改类的行为

//decorator是一个函数用于修改类的行为
    function test(is)
        return function(target)
            target.isTrue = is;
        
    
    @test(true)
    class Example = 
        constructor()
            console.log("test");
        
    
    console.log(Example.isTrue);

 

以上是关于ES6基础-7的主要内容,如果未能解决你的问题,请参考以下文章

ES7新特性

ES6ES7ES8ES9ES10新特性一览

ES6ES7ES8ES9ES10ES11新增特性一览-介绍

ES6ES7ES8ES9ES10ES11新增特性一览-介绍

ES6系列之变量声明let const

es6基础知识