前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >es6(五):class关键字(extends,super,static)

es6(五):class关键字(extends,super,static)

作者头像
用户1149564
发布2018-01-11 17:45:17
6550
发布2018-01-11 17:45:17
举报
文章被收录于专栏:Micro_awake webMicro_awake web

ES5中,生成对象通过构造函数

代码语言:javascript
复制
 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关键字,上面代码等价于下面:

代码语言:javascript
复制
 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

代码语言:javascript
复制
 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!当然如果没有构造函数,那么默认会生成一个构造函数

代码语言:javascript
复制
 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()//报错
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档