原型模式在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
}
}
我愿意使用原型模式,以避免过多的内存使用,并想知道ES6类是否确保?
类和构造函数只是语法糖。他们在内部编译成功能和原型。所以你可以使用两者,但更好地使用ES6方式。使用类语法使您的代码看起来更干净,面向对象。如果来自java / c ++等的任何人(纯OOP背景)来看看代码,他将会理解真正发生的事情
您的代码将不会被完全编译为原型模式,因为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泛型方法,它使用内置的对象方法转换对象原型
"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;
})();