原型模式在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类是否可以确保?
答案 0 :(得分:1)
您的代码不会完全按照原型模式进行编译,因为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;
})();
答案 1 :(得分:0)
类和构造函数只是语法糖。他们被编译为内部功能和原型。因此您可以同时使用两者,但最好以ES6方式使用。使用类语法可使您的代码看起来更简洁和面向对象。如果有来自Java / c ++等(纯OOP背景)的人来看看代码,他将了解真正的情况