I was reading the source code of backbone today to try and learn how it works. I tried to make my own initialize method that fires when a myModel is instantiated, but it doesn’t seem to work. (alerts “default hello”)
I was thinking that when myModel was created, it would copy the “this.initialize.apply” into myModel, and it would inherit the initialize method from Model’s prototype. If myMethod didn’t have an initialize method, it would look up the chain, but if myMethod does have it, it would use that instead. From what i’m (wrongly) thinking, myModel reads the apply like “myModel.initialize.appy(this, arguments)”, but it seems to be calling Models instead.
Any idea’s on where i’m going wrong? http://jsfiddle.net/LvjpK/
function Model () {
this.initialize.apply(this, arguments);
}
Model.prototype.initialize = function () {
alert("Default Hello");
};
myModel = {
initialize: function() {
alert("Hello from myModel");
}
};
var myModel = new Model();
With your
new Model()line, you’re creating a totally new object and putting a reference to it into themyModelvariable.The
initializefunction that you’ve defined onmyModelearlier has absolutely no relevance. It never gets into play. It just gets picked up by the garbage collector as soon as you lose a reference to it by overwriting themyModelvariable with it’s new value.