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

标签 javascript

探索 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在这里实际上意味着什么?它指的是功能点吗?在这种情况下,this 当然是 Point 的实例,因为它也引用 function Point,所以 _classCallCheck将始终返回true

最佳答案

So what does Point actually mean here? Does it refer to the function Point?

是的

<小时/>

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

var test = Point(); // THROWS ERROR

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

<小时/>

它强制您实例化一个新实例:

var test = new Point(); // VALID

关于javascript - 以松散模式将 ES6 编译为 ES5 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359318/

相关文章:

javascript - 去掉两个选项

javascript - Protractor 计数()期望意外失败

javascript - Symfony Assetic-URL中的part_1

javascript - IE8 .attachEvent() 错误

javascript - 防止 JavaScript window.getSelection() 循环引用

javascript - 无法在 react 中呈现组件

javascript - 布局和加载元素的异步问题

javascript - 使用 svg.js 制作位置动画的正确方法是什么

javascript - Jquery 函数可以在本地服务器上运行,但不能在实时服务器上运行?

javascript - Angular.js 将过滤器传递给指令双向 ('=' ) 属性