Class(类)
Class是ES6引入的最重要特性之一。在没有Class之前,我们只能通过原型链来模拟类。
Class Definition(类的定义)
-
class Shape {
-
constructor(name) {
-
this.name = name;
-
}
-
move(x, y) {
-
console.log(this.name + " Move to: " + x + "," + y);
-
}
-
}
上面定义了一个Shape类,他有一个属性 name 和一个方法 move(),还有一个构造函数。
调用Shape类
-
let shapA = new Shape("Shape A", 180, 240); // 输出: Shape A Move to: 180,200
-
shapA.move(240, 320); // 输出: Shape A Move to: 240,320
Class Inheritance(类的继承)
通过关键字 extends 来继承一个类,并且可以通过 super 关键字来引用父类。
-
class Rectangle extends Shape {
-
constructor(name) {
-
super(name);
-
}
-
area(width, height) {
-
console.log(this.name + " Area:" + width * height);
-
}
-
}
-
-
class Circle extends Shape {
-
constructor(name) {
-
super(name);
-
}
-
area(radius) {
-
console.log(this.name + " Area:" + 3.14 * radius * radius);
-
}
-
}
调用Rectangle、Circle类
-
let rectangleA = new Rectangle("Rectangle B");
-
let circleB = new Circle("Circle C");
-
rectangleA.move(100, 200); // 输出: Rectangle B Move to: 100,200
-
rectangleA.area(30, 40); // 输出: Rectangle B Area:1200
-
circleB.move(200, 300); // 输出: Circle C Move to: 200,300
-
circleB.area(50); // 输出: Circle C Area:7850
Getter/Setter
在Class内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
-
class People {
-
constructor(name) {
-
this._name = name;
-
}
-
get name() {
-
return this._name.toUpperCase();
-
}
-
set name(name) {
-
this._name = name;
-
}
-
sayName() {
-
console.log(this._name);
-
}
-
}
-
var p = new People("tom");
-
console.log(p.name); // TOM
-
p.name = "john";
-
console.log(p.name); // JOHN
-
p.sayName(); // john
Static Members(静态成员)
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
-
class F3 {
-
static classMethod() {
-
return 'hello';
-
}
-
}
-
F3.classMethod() // 输出: hello
-
var f3 = new F3();
-
// f3.classMethod(); // 输出: TypeError: f3.classMethod is not a function
-
静态属性指的是Class本身的属性,即Class.propname,而不是定义在实例对象(this)上的属性
-
class F4 {}
-
F4.prop = 5;
-
console.log(F4.prop) // 输出: 5
完整代码:https://github.com/guyoung/GyWxappCases/tree/master/ES6 |