I'm having some trouble figuring out how the prototype chain is set up given the following code.
var Model = {
prototype: {
init: function(){},
log: function(){ console.log('instance method log was called') }
},
log: function(){ console.log('class method log was called') },
create: function() {
var object = Object.create(this);
object.parent = this;
object.prototype = object.fn = Object.create(this.prototype);
return object;
},
init: function() {
var instance = Object.create(this.prototype);
instance.parent = this;
instance.init.apply(instance, arguments);
return instance;
}
}
var User = Model.create();
User.log(); // 'class method log was called'
// create a new method after creation
Model.warn = function() { console.warn('warn was called') }
User.warn() // 'warn was called'
var user = User.init();
user.log(); // 'instance method log was called'
Specifically this line confuses me in the create method:
object.prototype = object.fn = Object.create(this.prototype);
I understand how the create method is creating a new object who's prototype points back to Model, but the penultimate line seems to overwrite that prototype with a new object (Model.prototype). However, it seems the original prototype is still intact, as I can add methods to Model even after creating a new object, and the new object can still access it.
can someone shed some light on what is actually happening?
Edit - I should point out this code comes from Javascript Web Applications by O'reilly
thisandobjectare referring to the same thing inModel.create. If so, they're not.thisis a reference toModel, butobjectis a reference to a new object created fromObject.create(this). So when you doobject.prototype = ...whatever, you're not overwritingModel.prototype, but you are shadowing the.prototypeproperty that exists in the prototype chain ofobjectby placing a property with the same name directly onobject..prototypeproperty that is being set onobjecthas nothing to do with the prototype chain itself. Once you have created an object, it's not possible to change the prototype chain. So when a value is written toobject.prototype, it doesn't interfere at all with the relationship betweenobjectandModel. The only time setting a.prototypeproperty has an effect on the prototype chain, is when you change the.prototypeproperty of a constructor function, and then only future objects made from the constructor are affected by that change..prototypeproperty is definitely a pitfall for someone new to JS.