ES6中json的2个变动

  • 简写:名字和值雷同时,json能够能够简写
let a=12,b=5;let json = { a, b}console.log(json) // { a:12 , b:5 }
  • 省略function:json中的函数能够简写
let persen ={ name:'倩倩', age:18, showName(){  alert(this.name) }}persen.showName()

ES6与传统面向对象

传统面向对象:类和构造函数在一起,为对象增加办法时应用prototype。传统面向对象实例如下:

function Person(name,age){ this.name = name; this.age = age}Person.prototype.showName = function(){ console.log('我叫',this.name)}Person.prototype.showAge = function(){ console.log('往年',this.age,'岁')}var p = new Person('倩倩',18)p.showName()p.showAge()

ES6面向对象:将类和构造函数离开。

类:class

构造函数:constructor指生成完实例之后,本人就执行的函数。

class Person{ constructor(name,age){  this.name = name;  this.age = age; }  //给对象增加办法 showName(){  console.log('我叫',this.name) } showAge(){  console.log('往年',this.age,"岁") }}var p =new Person('倩倩',18);p.showName();p.showAge()

面向对象的继承

传统面向对象的继承:

应用apply办法,子类继承父类全副属性。

应用prototype办法,子类继承父类的办法。

传统面向对象的继承实例如下:

function Person(name,age){ this.name = name; this.age = age}Person.prototype.showName = function(){ console.log('我叫',this.name)}Person.prototype.showAge = function(){ console.log('往年',this.age,'岁')}function Worker(name,age,job){ Person.apply(this,arguments)//继承属性 this.job = job}Worker.prototype = new Person();//继承办法Worker.prototype.showJob = function(){ console.log('工作是',this.job);}var w = new Worker('倩倩',18,'打杂');w.showName();w.showAge();w.showJob();

ES6面向对象继承:

应用extends实现子类对父级的继承,super()将父类的属性继承过去。

class Person{ constructor(name,age){  this.name = name;  this.age = age;} showName(){  console.log('我叫',this.name) } showAge(){  console.log('往年',this.age,"岁") }}class Worker extends Person { constructor(name,age,job){   super(name,age)   this.job = job } showJob(){  console.log('工作是',this.job) }}var w = new Worker('倩倩',18,'打杂');w.showName();w.showAge();w.showJob()

对于super:

子类中有constructor,外部就要有super,因为子类没有本人的this对象,须要继承父类的this对象。

这里的super(name,age)就是调用父类的构造函数。

super尽管代表了Person的构造函数,然而返回的是子类Worker的实例。

ES6面向对象长处

ES6面向对象相比传统面向对象,语法简化

ES6语法规范、对立,适宜大我的项目开发,不易产生抵触。

ES6是零碎提供的规范语法,能够疏忽兼容性问题。