ES6 中的 JavaScript 原型(prototype)模式

标签 javascript prototype es6-class

原型(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/

相关文章:

javascript - 使用javascript在crm 2011中基于安全角色隐藏站点地图中的链接

javascript - 我的 `{{link-to}}` 助手之一正在触发页面重新加载。我如何找出导致该页面完全重新加载的原因?

javascript - HTML5 基于拖放事件的叠加层疯狂闪烁

javascript - 主干路由器和与网络服务器 Controller 的兼容性

javascript函数调用性能与new

javascript - 在仅 nodejs 环境中的 ES6 模块/类中定义 'real' 私有(private)方法,没有任何信息泄漏

angular - 如何使用类构造函数为类实例定义接口(interface)

c - 了解由于原型(prototype)不匹配而导致的意外结果 (C89)

javascript - 定位器无效错误

javascript - ES6 导入扩展类