Effectiveness of JS Object creation factory pattern vs. new

67 views Asked by At

It would seem that using the vanilla JS model for object (in OOP sense) creation:

function Point(x,y) {
  this.x = x
  this.y = y
}

Point.prototype.distSquared = function(p) {
  return (this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)
}

is more effective than factory pattern:

function makePoint(x,y) {

  const distSquared = (p) => {
    return (point.x - p.x) * (point.x - p.x) + (point.y - p.y) * (point.y - p.y)
  }

  let point = {
    x,
    y,
    distSquared
  }

  return point
}

because in the former case the public function distSquared is only declared once and all Points share it -- it's property of their common prototype, while in the latter case every Point has its own copy of distSquared.

Is this intuition correct? Does it have some practical consequences in terms of memory consumption, performance and so on?

0

There are 0 answers