metaprogramming javascript

Post on 26-Jan-2015

49.300 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

As presented at @media Ajax in London on the 20th November 2007.

TRANSCRIPT

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...

top related