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
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

6. Classes > Prototype Functions

Prototype Functions

In JavaScript, you can add functions and attributes to all instances of an object by adding those functions and attributes to the object’s prototype using the aptly named prototype attribute.

In CoffeeScript we can do this using the :: operator. Let’s add a size function to all instances of array. We want the size function to return the length of the array.

Example: (source: prototypes.coffee)


myArray = [1..10]

try
  console.log myArray.size()
catch error
  console.log error

Array::size = -> @length
console.log myArray.size()

myArray.push(11)
console.log myArray.size()


Example: (source: prototypes.js)


(function() {
  var myArray;

  myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  try {
    console.log(myArray.size());
  } catch (error) {
    console.log(error);
  }

  Array.prototype.size = function() {
    return this.length;
  };

  console.log(myArray.size());

  myArray.push(11);

  console.log(myArray.size());

}).call(this);


  

You are currently reading a PREVIEW of this book.

                                                                                        

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

  

Start a Free Trial