为了账号安全,请及时绑定邮箱和手机立即绑定

ECMAScript6.0新特性介绍第四篇

标签:
JavaScript

本节讲解ES6中如何实现面向对象以及JavaScript中是怎么实现对象的。ES6中的面向对象从语法上很像Java,它使用class关键字来定义一个类,使用constructor关键字来定义构造器,也就是说在ES6中构造器和类从写法上彻底地分开了,此外ES6的继承也很简单 直接一个extends关键字就可以搞定,不像JavaScript中写一大段代码,写起来特别繁琐。。

  • 使用JavaScript的方式实现面向对象
//javascript 中的面向对象
function human(name,age){
    this.name=name;
    this.age=age;
}
//通过原型添加方法
human.prototype.sayHello=function(){
    console.log('hello! i am '+this.name+'a '+this.age+'years old boy');
}
//创建human对象
var human=new human('tom',23);//构造函数与类相同
//调用human sayHello方法
human.sayHello();//输出 hello! i am tom a 23 years old boy
  • 使用ES6的方式实现面向对象
//class 关键字 构造器与类名分开
class person{
    constructor(name,age){
        this.name=name;
        this.age=age;

    }
    //class里面直接加方法 无需通过原型。
    sayHello(){
        console.log('hello! i am '+this.name+'a '+this.age+'years old boy');
    }
}
var person=new person('tom',23);//构造函数与类相同
person.sayHello();//输出 hello i am tom a 23 years old boy。
  • JavaScript中的继承
//javascript 中的继承,演示fireman 继承自human
function fireman(name,age,job){
    human.call(name,age);
    this.job=job;
}
fireman.prototype=new human();
fireman.prototype.constructor=human
fireman.prototype.action=function(name){
   console.log(`hello! i am a ${this.name} my job is ${this.job}`);
}
//创建
var fireman=new fireman('lisi',25,'saving life from the fire');//构造函数与类相同
fireman.sayHello();//输出 hello! i am lisi a 25 years old boy
fireman.action();//输出 hello! i am lisi my job is saving life from the fire
  • ES6中的继承
class fireman extends human{
    constructor(name,age,job){
        super(name,age);
        this.job=job;
    }
    action(){
        console.log(`hello i am ${this.name} my job is ${this.job}`);
    }
}
let a=new fireman('lisi',28,'saving life from the fire');
a.sayHello();/输出:hello! i am lisi ,a 28years old boy
a.action();//hello i am lisi ,my job is saving life from the fire

关于ES6的面向对象就介绍到这里。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消