关于前端:ES6新增语法三面向对象

4次阅读

共计 1885 个字符,预计需要花费 5 分钟才能阅读完成。

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 是零碎提供的规范语法,能够疏忽兼容性问题。

正文完
 0