用了很久的 es6,但都是为了项目而赶鸭子上架,没有真正去学习、掌握基本语法,所以我就借花献佛,一起巩固下~
大家知道,js 的传统方法是通过构造函数,定义并生成新对象的。现在 es6 提供了更接近传统语言的写法,那就是 Class(类)这个概念,作为对象的模版。
- 通过 class 关键字来定义类。
- class 可以看作只是一个语法糖,它的绝大部分功能,es5 都可以支持, 那 es6 的 class 写法只是让对象原型的写法更加清晰、面向对象编程的语法
// es5 定义类
function Person(x, y) {
this.x = x
this.y = y
}
Person.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')'
}
// es6 定义类
class Person {
constructor (x, y) {
this.x = x
this.y = y
}
toString() {
return '(' + this.x + ', ' + this.y + ')
}
}
通过对比,可以明显看出来,es5 的写法是传统的面向对象,es6 的类,完全可以看作构造函数的另一种写法。
es6 写法,可以看到里面有一个 constructor 方法,这就是构造方法,而this 关键字则代表实例对象
- 类的数据类型就是函数,类本身就指向构造函数。
- 构造函数的 prototype 属性,在 es6 的“类”上面继续存在。类的所有方法都定义在类的 prototype 属性上面。
class Person {
constructor(){}
toString(){}
toValue(){}
}
// 等同于
Person.prototype = {
toString(){},
toValue(){}
}
在类的实例上调用方法,就是调用原型上的方法。
另外,类的内部所有定义的方法,都是不可枚举的,与 es5 的行为不一致
接下来,我们进入正题,总结下 es6 类一些基本语法以及用法
- constructor方法
- 不存在变量提升
- Class表达式
- 私有方法
- this的指向
- 严格模式
- name属性
- 类的实例对象
constructor方法
- 它是类默认的方法,通过 new 生成对象实例时,自动调用。一个类必须有 constructor 方法,没显示定义,一个空的 constructor 会被自动添加。
class Person {
}
// 等同于
class Person {
constructor() {}
}
- constructor 方法默认返回的实例对象(即this), 可以指定返回另外一个对象。
class Person {
constructor() {
return Object.create(null);
}
}
new Person() instanceof Person // false
上面这个列子,constructor 返回一个全新的对象,所以导致实例对象不是Person 类的实例
- 类必须使用 new 调用,不然会报错。而普通构造函数可以不用 new 也能调用
class Person {
constructor() {
return Object.create(null)
}
}
Person() // TypeError: Class constructor Person cannot be invoked without 'new'
不存在变量提升
- 同 es5 不同,Class 不存在变量提升。如果在类使用使用前,定义在后,会报错。因为 es6 不会把类的声明提升到代码头部,原因与继承有关,必须保证子类在父类之后定义。
// 错误
new Person(); // ReferenceError
class Person {}
// 正确
{
let Person = class {};
class Children extends Person {
}
}
Class表达式
- 类也可以使用表达式的形式定义
const Person = class Per {
getAge() {
return Per.age
}
}
注意点:类的名字是 Person 而不是 Per,Per 只在 Class 的内部代码可用,指代当前类。
let inst = new Person();
inst.getAge() // Per
Per.age // ReferenceError: Per is not defined
Per只在 Class 内部有定义。
如果内部没有用到,可以省略 Per,如:
const Person = class { /* ... */ };
- 采用Class表达式,可以写出立即执行的 Class
let person = new class {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}('李斯');
person.sayName(); // "李斯"
私有方法
es6 不提供私有方法,只能通过变通方法模拟实现。
- 在命名上加以区别
class Widget {
// 公有方法
foo (baz) {
this._bar(baz)
}
// 私有方法
_bar(baz) {
return this.snaf = baz
}
}
_bar 方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。
- 将私有方法移出模块,因为模块内部的所有方法都是对外可见的
class Widget {
foo (baz) {
bar.call(this, baz)
}
}
function bar(baz) {
return this.snaf = baz
}
foo 是公有方法,内部调用了 bar.call(this, baz)。这使得 bar 实际上成为了当前模块的私有方法。
- 利用 Symbol 值的唯一性,将私有方法的名字命名为一个 Symbol 值
const bar = Symbol('bar');
const snaf = Symbol('snaf');
export default class myClass{
// 公有方法
foo(baz) {
this[bar](baz);
}
// 私有方法
[bar](baz) {
return this[snaf] = baz;
}
};
上面代码中,bar 和 snaf 都是 Symbol 值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。
this的指向
类的方法内部如果含有 this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
printName 方法中的 this,默认指向 Logger 类的实例。但是,如果将这个方法提取出来单独使用,this 会指向该方法运行时所在的环境,因为找不到 print 方法而导致报错
- 在构造方法中绑定 this,这样就不会找不到 print 方法了。
- 使用箭头函数。
- 使用 Proxy,获取方法的时候,自动绑定 this。
class Logger {
constructor() {
// 构造方法中绑定 this
this.printName = this.printName.bind(this);
// 使用箭头函数
this.printName = (name = 'there') => {
this.print(`Hello ${name}`);
};
}
}
// 使用 Proxy
function selfish (target) {
const cache = new WeakMap();
const handler = {
get (target, key) {
const value = Reflect.get(target, key);
if (typeof value !== 'function') {
return value;
}
if (!cache.has(value)) {
cache.set(value, value.bind(target));
}
return cache.get(value);
}
};
const proxy = new Proxy(target, handler);
return proxy;
}
const logger = selfish(new Logger());
严格模式
类默认就是严格模式,所以不需要使用 use strict 指定运行模式。
name属性
由于本质上,es6 的类只是 es5 的构造函数的一层包装,所以函数的许多特性都被 Class 继承,包括 name 属性。
class Point {}
Point.name // "Point"
name 属性总是返回紧跟在 class 关键字后面的类名。
类的实例对象
- 同 es5 生成类的实例对象的写法一样,使用 new 命令,否则也会报错
// 报错
var person = Person(1, 2);
// 正确
var person = new Person(1, 2);
- 同 es5 一样,实例的属性定义在原型上(即 class 上),除非显式定义在其本身(即在 this 对象上)
//定义类
class Person {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var person = new Person(2, 3);
person.toString() // (2, 3)
person.hasOwnProperty('x') // true
person.hasOwnProperty('y') // true
person.hasOwnProperty('toString') // false
person.__proto__.hasOwnProperty('toString') // true
上面可以看出,x 和 y 都是实例对象 person 自身的属性(定义在 this 变量上),所以 hasOwnProperty 方法返回 true,而 toString 是原型对象的属性(定义在 Person 类上),所以 hasOwnProperty 方法返回 false
- 同 es5 一样,类的所有实例共享一个原型对象。
var p1 = new Person(2,3);
var p2 = new Person(3,2);
p1.__proto__ === p2.__proto__ //true
p1 和p2 都是 Person 的实例,原型都是 Person.prototype,所以 proto 属性是相等的
当然也可以通过 proto 为 Class 添加方法,但是,因为会改变 Class 的原始定义,影响到所有实例,所以谨慎使用