简体   繁体   中英

JavaScript Prototype Pattern in ES6

The prototype pattern is implemented in ES5 as follows:

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;
};

on the other hand it's ES6 equivalent is defined (in here ) as:

class Shape {
  constructor (id, x, y) {
    this.id = id
    this.move(x, y)
  }
  move (x, y) {
    this.x = x
    this.y = y
  }
}

I am willing to use prototype pattern in order to avoid excessive memory usage and wondering if ES6 classes ensure that?

Your code will not be compiled exactly as prototype pattern because ES6 converters are functional hence what looks like this in ES6

class Shape {
constructor (id, x, y) {
this.id = id
this.move(x, y)
}
move (x, y) {
this.x = x
this.y = y
}
}

will look like this when converted you have createclass generic method which converts the object prototype using the inbuilt object methods

"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;

})();

class and constructors are just syntactic sugar. they get compiled down to function and prototype internally. so you can use both but better to use in ES6 way. using class syntax makes your code looks cleaner and object-oriented. if any person from java/c++ etc (pure OOP background) comes and see the code he will understand what's really going on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM