在探索 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/