015 Class基本语法
1、类的由来
JavaScript语言中,生成实例对象的传统方法是通过构造函数
function Point (x,y){
this.x=x;
this.y=y;
}
Point.prototype.toString=function(){
return'('+this.x+','+this.y+')';
};
var p =new Point(1,2);
ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类
基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已
class Point{
constructor(x,y){
this.x=x;
this.y=y;
}
toString(){
return'('+this.x','+this.y+')';
}
}
2、constructor方法
constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须由constructor()方法,如果没有显示定义,一个空的constructor()方法会被默认添加
class Point{
}
//等同于
class Point{
constructor(){}
}
3、类的实例
生成类的实例的写法,于ES5完全一样,也是使用new命令
class Point{
//...
}
//报错
var point=point(2,3);
//正确
var point =new Point(2,3);
4、注意点
不存在提升
类不存在变量提升(hoist),这一点与ES5完全不同
new Foo();//ReferenceError
class Foo{}



浙公网安备 33010602011771号