透过babel,看看es6的class实现

666 阅读1分钟

Babel是一个JavaScript语法转换器,能够将es5+的代码转换为向后兼容的JavaScript语法。我们一起来看个例子。

class Animal {}

上面代码,通过es6的class关键字声明一个Animal类,通过babel转化后得到

var _instanceof = function(left, right) {
    if (right != null &&
        typeof Symbol != 'undefined' &&
        right[Symbol.hasInstance]
    ) {
    	return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
};

var _classCallCheck = function(instance, Constructor) {
    if (_instanceof(instance, Constructor)) {
    	throw new TypeError('Cannot call a class as a function');
    }
};

var Animal = function Animal() {
    _classCallCheck(this, Animal);
};

上面代码可以得出以下几点结论:

  1. 只能通过new实例化Animal类,不能以函数方式直接调用;
  2. 在判断某个对象是否是构造器的实例时,可以借助Symbol.hasInstance方法;

**Symbol.hasInstance**用于判断某对象是否为某构造器的实例

class A {
    console.log(A[Symbol.hasInstance](this));
}

A(); // false

new A(); // true

上面代码,直接调用方式,A内部的this执行window,因此不是A的实例;而new的方式,this确实代表的是A的实例。