类
类是用于创建对象的模板。JavaScript中生成对象实例的方法是通过构造函数,这跟主流面向对象语言(java,C#)写法上差异较大,如下:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 1);
ES6 提供了更接近Java语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class
关键字,可以定义类。
如下:constructor()
是构造方法,而this
代表实例对象:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
类的数据类型就是函数,它本身就是指向函数的构造函数:
// ES5 函数声明
function Point() {
//...
}
// ES6 类声明
class Point {
//....
constructor() {
}
}
typeof Point // "function"
Point === Point.prototype.constructor // true
在类里面定义的方法是挂到Point.prototype
,所以类只是提供了语法糖,本质还是原型链调用。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x &