Gabriel Roda Eugen Bach Gabriel Roda Eugen Bach - 25 days ago 20
Javascript Question

Difference between object and object.prototype in Javascript

Ok so here's a bit of code that i am working with atm.

My Problem is that I don't really get the difference between an object and an object prototype. Up until now I thought, if I make a new Object, e.g. new Memory, this inherits all the properties I declared in Memory. In my code, however, i need to add options to Memory.prototype.

So my core question is: What is the difference between properties of the object and properties of the object.prototype?

var createMemory = function createMemory() {
new Memory( { wrapperID: 'memory-game'} );
};

var Memory = function (options) {

//check for required options
if ((options.wrapperID === undefined)
) {
console.error('ERROR: not all requried options given. wrapperID is requried!');
return false;
}

// hardcoded values
this.options.availableCards = 22;
this.options.cols = 4;
this.options.rows = 4;

this.options.flipTime = this.options.flipTime || 1;
this.options = extend({}, this.options);
extend(this.options, options);
//this._init();
};

Memory.prototype.options = {
onGameEnd: function () {
return false;
}
};

Answer

You forgot to return the new object in createMemory.

A few other fixes as well and i had to invent an extend function, since you didn't include yours.

//Extend function
function extend(a, b) {
    for (var i in b) {
      if (b.hasOwnProperty(i)) {
        a[i] = b[i];
      }
    }
    return a;
  }
  //Memory class

function Memory(options) {
  //check for required options
  if ((options.wrapperID === undefined)) {
    console.error('ERROR: not all requried options given. wrapperID is requried!');
    return false;
  } // hardcoded values

  this.options.availableCards = 22;
  this.options.cols = 4;
  this.options.rows = 4;
  this.options.flipTime = this.options.flipTime || 1;
  this.options = extend({}, this.options);
  extend(this.options, options);
  //this._init();
};
Memory.prototype.options = {
  onGameEnd: function() {
    alert("Inherited")
  }
};
//Instantiater
function createMemory() {
  return new Memory({
    wrapperID: 'memory-game'
  });
};

//Instantiate
var m = new createMemory();
//Call inherited
console.log(m);
m.options.onGameEnd();

Properties of the Object is specific to that instance of the object, while properties of the Prototype is shared among instances of the object.

If, for instance, you have an ID number for each instance, then the ID property needs to be on the Object since it would be unique to that instance.

Conversely, if you had a method that was the exact same of all instances, then you can save on memory by putting it in the Prototype and simply inherit it.

Comments