-3

Given:

var x = function () {

};  
x.prototype = { abc: 25 };

Can someone explain to me what this means. Could this be done all inside a function without the .prototype?

var x = function () {
  // something here ?
};
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • The following should explain a lot:http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 prototype saves memory and CPU as well as enables you to use recognizable OO patterns – HMR Jun 27 '14 at 06:41
  • You can do `this.abc = 25` inside the constructor, which is roughly the same. – Felix Kling Jun 27 '14 at 06:45

1 Answers1

2

Prototypes are how the class model works in JavaScript - you've created a class x that has a property abc which defaults to 25:

var obj = new x();
alert(obj.abc);   // 25

The function x is the class constructor, it is called when a new instance of that class is created and can initialize it. And that means of course that you can just set the abc property there:

var x = function()
{
  this.abc = 25;
};
var obj = new x();
alert(obj.abc);   // 25

This is supposedly the less efficient approach however:

  • You have to manipulate each object created rather than setting the property on the prototype once and forever.
  • The property is stored on each object and consumes memory each time, as opposed to being stored once on the prototype.

ECMAScript Harmony has a nicer syntax for defining classes and prototypes, however this one isn't implemented in any browser yet:

class x {
  constructor() {
    ...
  }

  public abc = 25;
}

This is equivalent to your code defining the prototype, merely grouping related operations a little better.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126