Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. MVC and Classes > Adding Functions to Classes

Adding Functions to Classes

Adding class functions to a constructor function is the same as adding a property onto any object in JavaScript:

Person.find = function(id){ /*...*/ };

var person = Person.find(1);

To add instance functions to a constructor function, you need to use the constructor’s prototype:

Person.prototype.breath = function(){ /*...*/ };

var person = new Person;
person.breath();

A common pattern is to alias a class’ prototype to fn, which is a bit less verbose:

Person.fn = Person.prototype;

Person.fn.run = function(){ /*...*/ };

In fact, you’ll see this pattern throughout jQuery plug-ins, which essentially just add functions to jQuery’s prototype, aliased to jQuery.fn.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint