Metaprogramming Javascript

Preview:

DESCRIPTION

Metaprogramming, writing code that augments itself at runtime, is a very powerful technique gaining popularity in scripting languages like Python and Ruby but surely little old JavaScript isn't flexible enough to do this? Think again. In this presentation, we'll deconstruct the features of JavaScript that allow metaprogramming then move on to combining these to produce elegant solutions to real world tasks. In the process, we'll take an in-depth look at closures, functional programming, prototype inheritance and more. Bring your best brain, you'll need it.

Citation preview

Metaprogramming JavaScript

Dan Webb (dan@danwebb.net)

What?

the writing of computer programs that write or manipulate other programs (or themselves) as theirdata”“

With JavaScript?!★ Small and fiesty but widely misunderstood

★ Relies on few but powerful constructs

★ You can work with functions, arguments, built-ins types and mechanisms like inheritance at runtime

★ Techniques underpin many JS libraries

JavaScript Exposed:Objects Out Of

Control!

Play along!

4 building blocks

(Nearly) everything is a hash

numberstring

booleanundefined

everything else is an Object

This works with any object

Expandos: a special case

Inspecting objects

Inspecting types

Wha?!

First typeofthen instanceof

Functions are Objects

'Methods' are just functions that are

assigned to a property of an object

arguments

Functions can return other functions

Closure

Back to wikipedia...

A closure occurs when a function is defined within another function, and the inner function refers to local variables of the outer function. “ ”

Why is that useful?

Functions can be used to make objects

Constructor functionsare just functions

The magic is inthe new operator

inheritance

The point is:its all just functions,

objects and properties

We can hack it all.

So what can you do with this stuff?

Patch holes in bad implementations

Self optimising code

Pretty APIs

Domain Specific Languages

DOMBuilderhttp://danwebb.net/lowpro

DIY language features

John Resig's method overloading

http://ejohn.org/blog/javascript-method-overloading/

Prototype 1.6 Classeshttp://prototypejs.org/learn/class-inheritance

and a lot more...

Looking back...★ JavaScript is small but totally flexible

★ A handful of techniques provide everything you need

★ It's all about objects, properties and functions

★ Don't worry if its not all sunk in. Have a play around. Slides will be available.

Coming Soon...