1

I'm accustom to work with constructor-functions this way:

function Computer(ram) {
  this.ram = ram;
}

// Defining a property of the prototype-
// object OUTSIDE of the constructur-
// function.
Computer.prototype.getRam = function() {
  return this.ram + ' MB';
}

I define and initialize values within the constructor. Methods are attached upon the prototype-object outside the constructor-function.

Yesterday I've seen these technique:

function Car(maxSpeed) {
  this.maxSpeed = maxSpeed;
  // Defining a property of the prototype-
  // object WITHIN the constructur-
  // function.
  Car.prototype.getMaxSpeed = function() {
    return this.maxSpeed + ' km/h';
  }
}

The method is defined within the constructor-function => Without creating at least one object the method doesn't exist.

What I always consider a bit weird concerning the first approach is that someone can call the method upon the constructor-function / -object. Then all properties which use the this-keyword return undefined. With the second technique an error is thrown.

What are the advantages and disadvantages of both techniques?

Which one should I prefer / avoid and for what reasons?

cluster1
  • 4,968
  • 6
  • 32
  • 49
  • 1
    The second option is NOT recommended. It has several downsides. – jfriend00 Feb 14 '16 at 09:05
  • What are downsides? Do you have a link to another question or some article please? – cluster1 Feb 14 '16 at 09:08
  • The first one is the correct way of defining a function and setting prototype properties. Second is not the correct one. With first one, even if function `Computer.prototype.getRam` is available for someone to call, it has to called either on a instance of `Computer` like `comp1.getRam()` or using prototype like `Computer.prototype.getRam.call(comp1)`. – Royal Pinto Feb 14 '16 at 09:09
  • I marked your question as a duplicate of another question where the downsides are described. No point in duplicating that here. – jfriend00 Feb 14 '16 at 09:10
  • @jfriend00 Can you give me the link to the question please? – cluster1 Feb 14 '16 at 09:13
  • Look right at the top of your question. It's right there. That's where a link to the duplicate appears when your question is marked a duplicate. – jfriend00 Feb 14 '16 at 09:14
  • Got it. :) Thanks a lot. – cluster1 Feb 14 '16 at 09:19

0 Answers0