亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消