在ES5中我们通常通过构造函数,定义并生成新对象。
例如:
function Point(name,age){
this.name=name;
this.age=age;
}
Point.prototype={
Who:function(){
return "My name is "+this.name+",My age is "+this.age;
}
}
var p=new Point("ND",25);
console.log(p.Who()) //My name is ND,My age is 25
而在ES6中引入了class的概念,ES6的class可以看成一个语法糖(语法糖:指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。)
现在我们可以用ES6的class这样定义一个Point,
class Point{
constructor(name,age){
this.name=name;
this.age=age;
}
Who(){
return "My name is "+this.name+",My age is "+this.age;
}
}
var p=new Point("ND",25);
console.log(p.Who()) //My name is ND,My age is 25