Difference between object and object.prototype in Javascript -
this question has answer here:
- how new operator work in javascript? 2 answers
ok here's bit of code working atm.
my problem don't difference between object , object prototype. until thought, if make new object, e.g. new memory, inherits properties declared in memory. in code, however, need add options memory.prototype.
so core question is: difference between properties of object , properties of object.prototype?
edit: specify: in memory function log this.options. doesn't work, unless include memory.prototype.options = {...}. if new memory inherits properties memory , defined e.g this.options.availablecards above, why need add options prototype?
var creatememory = function (){ new memory( {wrapperid: 'memory-game'} ); }; var memory = function (options) { //check required options if ((options.wrapperid === undefined)){ console.error('error: not required options given. wrapperid required!'); return false; } //hardcoded values this.options.availablecards = 22; this.options.cols = 4; this.options.rows = 4; this.options.fliptime = this.options.fliptime || 1; //set default this.options = extend({}, this.options); extend(this.options, options); //this._init(); console.log(this.options); }; // why required? memory.prototype.options = { ongameend: function(){ return false; } }; creatememory();
you forgot return new object in creatememory
.
a few other fixes , had invent extend
function, since didn't include yours.
//extend function function extend(a, b) { (var in b) { if (b.hasownproperty(i)) { a[i] = b[i]; } } return a; } //memory class function memory(options) { //check required options if ((options.wrapperid === undefined)) { console.error('error: not requried options given. wrapperid 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 object specific instance of object, while properties of prototype shared among instances of object.
if, instance, have id number each instance, id
property needs on object since unique instance.
conversely, if had method exact same of instances, can save on memory putting in prototype , inherit it.
Comments
Post a Comment