zoukankan      html  css  js  c++  java
  • 1.class基本语法——ES6类和继承

    1.定义

    // es5封装一个对象
    function Person(name,age){
        this.name = name;
        this.age = age;
    }
    
    Person.prototype.run = function(){
        console.log(this.name+" is running");
    }
    
    let p = new Person('lily');
    p.run();
    
    
    // ES6类的定义
    calss Person{
        //构造方法
        constructor(name,age){
            this.name = name;
            this.age = age;
        }
    
        //方法
        /*
            函数的定义一定要用简写的方式,必须省略function
            写在class中的方法,是定义在类的原型上的
        */
        run(){
            console.log(this.name+" is running");
        }
    }
    
    //实例化
    let p = new Person('lily',300);
    p.run();
    console.log(p);

    总结:
    1.class中的方法都是定义在prototype上
    2.class中的方法都必须是简写,不带function
    3.calss中的构造函数用counstructor来定义
    4.class类方法,不能直接调用,必须实例化

    2.class中的getter和setter

    class Animal{
        set prop(name){
            this.name = name;
        }
        get prop(){
            return this.name;
        }
    
        set age(value){
            if(value<13){
                this.ages = value;
            }else{
                this.ages = 0
            }
        }
        get age(){
            return this.age
        }
    }
    
    /*
        当没有constructor,系统会默认一个空参
    */
    let ani = new Animal();
    ani.prop = "tiger";
    console.log(ani.pro);
    
    ani.age = 13;
    console.log(ani.age);

    3.静态方法和静态属性

    // 传统的方法定义
    function Person(){}
    
    Person.eat = function(){
        console.log('eating');
    }
    
    person.eat();
    
    
    // es6
    class Animal(){
        constructor(color){
            this.color = color;
        }
    
        static run(){
            //静态方法中的this是指向类本身就是Animal本身,不是指向new实例化的
            console.log(this);
        }
    }
    let rabbit = new Animal('white');
    Animal.run();//'undefined'
    
    
    let rabbit = new Animal('white');//black
    //给class添加静态属性
    Animal.color = 'black';
    Animal.run();//black

    4.new target


    构造函数被调用的时候,this指向谁
    只有通过new调用构造函数里,new.target才指向构造函数
    其它情况都返回undefined

    function Person(){
        console.log(new.target);
    }
    new Person();//指向Person
    
    Person.call();
    Person.apply();
    Person();
    
    ====
    
    function Person(){
        console.log(new.target);
    
        if(new.target === Person){
            this.name = name;
        }else{
            thorw new Error('只能通过new来调用');
        }
    }
    new Person();//指向Person,所有不报错
    
    
    Person.call();//报错
    Person.apply();//报错
    Person();//报错
  • 相关阅读:
    关于有序查找的随笔
    Spring框架(一) 创建bean
    Linux常用命令
    Spring框架(二) bean的歧义性
    java实现图片文字识别的两种方法
    分享基于分布式Http长连接框架代码模型
    分享基于分布式Http长连接框架设计模型
    无限树Jquery插件zTree的使用方法
    分享基于分布式Http长连接框架
    使用vs编译事件来动态发布配置文件
  • 原文地址:https://www.cnblogs.com/lisa2544/p/15666603.html
Copyright © 2011-2022 走看看