Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

Javascript prototypes

Andrew Hayward (a friend from Uni who has recently started blogging) has been playing with javascript’s prototypes. prototype is a value related to a particular class from which all instances of that class are created—only in javascript classes are actually functions... and then it all gets really complicated.

Anyway, Andy’s experiments concern using the prototype property to add new methods to javascript’s built in classes such as String, Array and even Object. He uses this trick to add useful methods such as String.trim(), Array.implode() and Object.dump(). It looks remarkably useful both for debugging and for making javascript do more stuff in less lines of code by adding additional layers of abstraction to the core language.

We’ve been looking at javascript in our “Concepts of Programming Languages” course this semester and it’s proving a much more interesting language than I had originally thought.

This is Javascript prototypes by Simon Willison, posted on 19th March 2003.

View blog reactions

Next: Dithered DOM scripts

Previous: Haunted by old hacks

4 comments

  1. Thanks for the link, but you've got the permalink a little wrong! Unless, or course, you intended to link to the comments form!

    Andrew Hayward - 19th March 2003 10:17 - #

  2. Yes. ECMAScript rocks. Did you know every object can be used like an array? function obj() { this.foo = "in foo"; this.bar = "in bar"; } function doload() { var o = new obj(); alert(o.foo); alert(o["bar"]); o["waka"] = 'in waka'; alert(o.waka); o.newFunc = function () { alert('in newFunc') }; o.newFunc(); //pops up dialog with 'in newFunc' alert(o.newFunc); //pops up dialog with string of function contents o.nextFunc = "alert('in nextFunc');"; o.nextFunc(); } There's all kinds of really cool stuff you can do in ECMAScript. I love it. If you want to learn all kinds of cool tricks, check out http://www.youngpup.net/ components. Aaron Boodman knows all the ins and outs of JavaScript. It's really good stuff.

    Jeremy Dunck - 21st March 2003 15:33 - #

  3. err.. Preview would help. :)

    Jeremy Dunck - 21st March 2003 15:34 - #

  4. Ugh. I thought the prototype was rather run-of-the-mill stuff. I was thrilled with the ability to dynamically construct regular expressions and functions. :) Anyways, yes, ECMAScript treats Objects as Associative Vectors, and everything except operators/messages are treated as Objects (including boolean). This is done (in at least two engines) by keeping _one_ Boolean Object, and just "loading" the current item into it's value before calling any methods. It means there's no allocation overhead to make all the primitives Object Oriented by behavior.

    Dan - 5th November 2005 11:37 - #

Comments are closed.

Previously hosted at http://simon.incutio.com/archive/2003/03/19/javascriptPrototypes

A django site