Search code examples
javascriptspine.js

why does spine.Model have functions with the same name in the prototype


I am trying to understand how it works

Why do functions have the same name in the prototype and how are they being used if the function for example Model.fromForm takes precedence over the prototype one. I mean the declarations are made in the base class/object. What exactly is happening when you create a model from that base class/object?

Also I have another question but I will wait for this one first.

thanks, Richard


Solution

  • The Spine model object and "instances" of the model are different objects, so different functions are evaluated. There is no precedence or overloading here. For example (in coffeescript) the following does the same thing:

    YourModel instance = YourModel.fromForm(form) # Uses the model object fromForm
    

    and

    YourModel instance = new YourModel
    instance.fromForm(form) # Uses the prototype fromForm
    

    If you look at the source code, you can see why it's equivalent; the object fromForm is simply declared as this.fromForm, and it calls the prototype one:

    @fromForm: ->
      (new this).fromForm(arguments...)