class总览:
- ES6 中的 class 可以看做是一个语法糖,它的功能用ES5 也可以实现,只是写法更加清晰明了(因为更像面向对象编程的语法);
- ES6 中类和模块内部都是默认使用严格模式,无需再加上”use strict”;
- class 的数据类型是”function”,因为类本身其实就是个构造函数;
上实例:
class Test {
constructor (x, y) { this.x= x; this.y = y; }
mix () { return '('+ this.x+ '-'+ this.y+ ')'; }
toStr () {} //方法间不需要用逗号隔开
toNum () {}
}
typeof Test //"function" 说明类的数据类型是函数
Test === Test.prototype.constructor //true 说明类本身就指向构造函数
let test = new Test(1,3); //必须用new 来调用,否则报错
//在类的实例上调用方法,实际上就是调用原型上的方法:
test.mix(); //(1-3)
test.constructor === Test.prototype.constructor
//true 说明实例的constructor 方法就是Test 类原型的constructor 方法
另外,可以用Object.assign
方法一次向类的原型上添加多个方法
class Test {
constructor (x, y) {
this.x= x;
this.y = y;
}
Object.assign (Test.prototype, {
toStr () {}, //需要加上逗号隔开各个方法
toNum () {}
});
}
1、constructor 方法
如果不加constructor 方法,引擎会帮你加一个空的constructor 方法;
这个constructor 方法默认返回实例对象(也就是this),如果手动去返回另一个对象,会导致实例对象不是 这个类的实例;
class Test {
constructor () {
return Object.create(null);
}
}
new Test() instanceof Test // false
let test = new Test(); //必须用new 来调用,否则报错