您的位置:首页 > 其它

ES6的class方法基本用法

2016-11-28 00:00 225 查看
摘要: ES6的class方法基本用法

在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ES6 class类