原型(prototype)模式在 ES5 中的实现如下:
var Shape = function (id, x, y) {
this.id = id;
this.move(x, y);
};
Shape.prototype.move = function (x, y) {
this.x = x;
this.y = y;
};
另一方面,它的 ES6 等效项定义(在 here 中)为:
class Shape {
constructor (id, x, y) {
this.id = id
this.move(x, y)
}
move (x, y) {
this.x = x
this.y = y
}
}
我愿意使用原型(prototype)模式以避免过多的内存使用,并且想知道 ES6 类是否能确保这一点?
最佳答案
您的代码不会完全按照原型(prototype)模式进行编译,因为 ES6 转换器是功能性的,因此 ES6 中看起来像这样
class Shape {
constructor (id, x, y) {
this.id = id
this.move(x, y)
}
move (x, y) {
this.x = x
this.y = y
}
}
转换时看起来像这样,你有 createclass 通用方法,它使用内置对象方法转换对象原型(prototype)
"use strict";
function _instanceof(left, right) {
if (
right != null &&
typeof Symbol !== "undefined" &&
right[Symbol.hasInstance]
) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _classCallCheck(instance, Constructor) {
if (!_instanceof(instance, Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var Shape =
/*#__PURE__*/
(function() {
function Shape(id, x, y) {
_classCallCheck(this, Shape);
this.id = id;
this.move(x, y);
}
_createClass(Shape, [
{
key: "move",
value: function move(x, y) {
this.x = x;
this.y = y;
}
}
]);
return Shape;
})();
关于ES6 中的 JavaScript 原型(prototype)模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55235969/