js中的类
之前在javascript没有类这样的概念,而是构造函数来定义某一种有着相似属性的“类”。然后通过new 运算符来获得该”类”的实例,通过原型链来继承它的父类的属性和方法。
//构造函数
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 Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
注意,定义“类”的方法的时候,前面不需要加上`function`这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。
class语法糖
基本上,ES6 的class
可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class
写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
//使用class构造函数的使用
class Bar {
doStuff() {
console.log('stuff');
}
}
var b = new Bar();
b.doStuff() // "stuff"
//构造函数的`prototype`属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的`prototype`属性上面。
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
//在类的实例上面调用方法,其实就是调用原型上的方法。
class B {}
let b = new B();
b.constructor === B.prototype.constructor // true
class的继承
通过关键字 extends 来继承一个类,并且,可以通过 super 关键字来引用父类。
class People {
constructor(name) { //构造函数
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Student extends People {
constructor(name, grade) { //构造函数
super(name); //调用父类构造函数
this.grade = grade;
}
sayGrade() {
console.log(this.grade);
}
}
//class.extend继承的本质还是prototy
extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
参考阮一峰的es6教程