JavaScript ES6 中的原型模式

JavaScript Prototype Pattern in ES6

原型模式在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 类 是否确保了这一点?

class 和构造函数只是语法糖。它们在内部被编译成功能和原型。所以你可以同时使用两者,但最好以 ES6 方式使用。使用 class 语法使您的代码看起来更清晰且面向对象。如果来自 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;

})();