• 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);
  • 相关阅读:
    【算法习题】青蛙跳台阶
    【转】从PowerDesigner概念设计模型(CDM)中的3种实体关系说起
    redis常用链接
    读书笔记——《redis入门指南(第2版)》第四章 进阶——4.1-5
    查询linux计算机的出口ip
    读书笔记——《redis入门指南(第2版)》第三章 入门
    vmware中的linux虚拟机配置以nat模式上网,并用xshell连接该虚拟机
    每日代码系列(1)
    第一次尝试自己编写
    原型模式
  • 原文地址:https://www.cnblogs.com/webcyh/p/11461284.html
Copyright © 2020-2023  润新知