es6 class

class语法是es6新加的语法,用于生成一个类,es5时生成类是通过构造函数,看着特别不舒服。

es5声明类:

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

class声明一个同样的类:

//    class pointClass{
//        constructor(x,y){
//            this.x=x;
//            this.y=y;
            
//        }
//
//        toString(){
//            return '('+this.x+','+this.y+')'
//        }
//    }

class里面还有静态方法只有这个类自己可以调用,只需要在方法面前加一个static

(只有静态方法没有静态实例)

class A{

    construcor(){

    }

     static staticFuc(){

        console.log("static_fuc");    

}

}

A.staicFuc();//static_fuc

class 中的set  和get:用于拦截实例的变化

class my_class{

    constroctor(){

        this.props=1;

    }

        set props(value){

            console.log(value);

        }

        get props(){

                console.log("getter);

           }

   }

let inst=new my_class();

inst.props=123;//123

inst.props//getter


类的继承:子类会继承父类的方法和变量

 
class Foo{
    static fa_method(){
        return "hello"
    }
}

class Bar extends Foo{

}
console.log(Bar.fa_method());

super的用法:它既可以当函数使用亦可以当对象使用

(1)super作为函数调用时代父类的构造函数,且子类的构造函数必须执行一次super

即有构造函数就必须执行super//否则会报错

class A{}

class B extend A{

    constructor(){

        super()

    }

}

(2) super作为对象时普通方法中指向父类的原型对象,静态方法中指向父类

也就是说当对象使用时子类中可以利用super调用父类的方法

class A{

    p(){

    }

}

class B extends A{

    constructor(){

        super()

        console.log(super.p());

    }

}

注意:父类方法中的this指向子类

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值