zoukankan      html  css  js  c++  java
  • es6(五):class关键字(extends,super,static)

    ES5中,生成对象通过构造函数
     1 function A(name,age){
     2       this.name=name;
     3       this.age=age
     4     }
     5     // 在A的prototype属性上定义一个test方法,即A生成的实例化对象的原型对象上的方法
     6     A.prototype.test=function(){
     7       return this.name+' '+this.age
     8     }
     9 
    10     var a1=new A('apple',100)
    11     console.log(a1.test())//apple 100
    es6中,引入了class关键字,上面代码等价于下面:
     1 class B{
     2       constructor(name,age){
     3         this.name=name
     4         this.age=age
     5       }
     6       test(){
     7         return this.name+' '+this.age
     8       }
     9     }
    10     var b1=new B('apple',100)
    11     console.log(b1.test())//apple 100
    需要注意的一点是:类和模块中默认使用的就是严格模式
     
    class中的静态方法:static
     1 class C{
     2       //没有写上constructor,默认会生成一个空的构造函数
     3       static foo(){//注意:class里面函数不用添加function;
     4       // 函数前面添加一个static关键字,表明这是一个静态方法,不会被实例继承,只能通过类来调用
     5         console.log(100)
     6       }
     7     }
     8     let c1=new C()
     9     // c1.foo()报错
    10     C.foo()//100

    继承:class可以通过extends关键字继承,对比es5修改原型链简单直观方便许多

    注意:子类中如果写了构造函数contructor,那么一定要在里面使用super方法,同时只有使用了super方法才能使用this!当然如果没有构造函数,那么默认会生成一个构造函数
     1 class D{
     2       constructor(age,email){
     3         this.age=age
     4         this.email=email
     5       }
     6       static test(){
     7         console.log(10)
     8       }
     9     }
    10     class E extends D{
    11       constructor(age,email,weight){
    12         super(age+'E',email+'E')//这里的super指向的是父类
    13         this.weight=weight
    14       }
    15     }
    16     let e1=new E(10,'100@qq.com',100)
    17     console.log(e1)//E {age: "10E", email: "100@qq.comE", weight: 100}
    18     E.test()//10,说明父类的静态方法可以被子类继承;但同理实例对象无法访问
    19     // e1.test()//报错
  • 相关阅读:
    项目冲刺-第一天
    第四次个人作业-关于微软必应词典客户端 的案例分析
    第三次作业-结对编程
    学院教师开课管理网站项目
    使用Git进行代码管理的心得--github for windows
    十天冲刺---Day8
    十天冲刺---Day7
    十天冲刺---Day6
    十天冲刺---Day5
    十天冲刺---Day4
  • 原文地址:https://www.cnblogs.com/why-not-try/p/8081674.html
Copyright © 2011-2022 走看看