繁体   English   中英

以松散模式将ES6编译为ES5构造函数

[英]Compiling ES6 to ES5 constructor in loose mode

在《 探索ES6》一书中,我正在阅读有关如何在松散模式下将构造函数编译为ES5的内容。 一个例子是这样的:

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return `(${this.x}, ${this.y})`;
    }
}

编译成这样:

"use strict";

function _classCallCheck(instance, Constructor) {
  if(!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var Point = (function () {
    function Point(x, y) {
        _classCallCheck(this, Point);

        this.x = x;
        this.y = y;
    }

    Point.prototype.toString = function toString() { // (A)
        return "(" + this.x + ", " + this.y + ")";
    };

    return Point;
})();

我不明白这一行:

_classCallCheck(this, Point);

那么Point在这里实际上意味着什么? 它是否指向function Point 在这种情况下, this当然是Point的实例,因为它也引用了function Point ,因此_classCallCheck将始终返回true

那么Point在这里实际上意味着什么? 它是否指向功能Point?


_classCallCheck所做的是检查是否已创建Point类的新实例。 它阻止某人执行以下操作:

var test = Point(); // THROWS ERROR

在前面的片段示例_classCallCheck(this, Point)this将是此代码的外部范围(可能是窗口)的任何范围。


它迫使您实例化一个新实例:

var test = new Point(); // VALID

那么Point在这里实际上意味着什么?

这是Point函数,存储在var Point

在这种情况下,这当然是Point的实例,因为它也引用了Point函数,因此_classCallCheck将始终返回true。

不是这样 这很容易调用Point以这样一种方式, this不是一个实例Point ES6类就其本质而言可以防止以这种方式调用类名,但是ES5不能,因此_classCallCheck可以确保保留ES6行为。 注意:

 "use strict"; function _classCallCheck(instance, Constructor) { if(!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Point = (function () { function Point(x, y) { _classCallCheck(this, Point); this.x = x; this.y = y; } Point.prototype.toString = function toString() { // (A) return "(" + this.x + ", " + this.y + ")"; }; return Point; })(); // Invalid call prevented by _classCallCheck Point(1, 2); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM