JavaScript Enlightenment

29
JavaScript Enlightenment Johnathan Hebert 1

description

JavaScript Enlightenment. Johnathan Hebert. Agenda. Introductions Presentation Brief history of JavaScript Objects in depth Functions in depth A few tricks Questions. It is (finally) getting better. Invented by Brendan Eich @ Netscape in 1995 Standardized by Ecma in 1997 (Ecma-262) - PowerPoint PPT Presentation

Transcript of JavaScript Enlightenment

Page 1: JavaScript Enlightenment

1

JavaScript Enlightenment

Johnathan Hebert

Page 2: JavaScript Enlightenment

2

Agenda

• Introductions• Presentation– Brief history of JavaScript– Objects in depth– Functions in depth– A few tricks

• Questions

Page 3: JavaScript Enlightenment

3

It is (finally) getting better• Invented by Brendan Eich @ Netscape in 1995• Standardized by Ecma in 1997 (Ecma-262)• 3rd Edition standardized in Dec 1999

– Untouched for 10 years, this is the one you know• 4th Edition was abandoned

– Vendor disagreements• 5th Edition standardized in Dec 2009

– Bug fixes, enhanced built-in objects, but no new syntax– Shipped in Chrome, Firefox, Safari, Opera and IE9+

• 5.1 Edition standardized in Jun 2011– Fixes errata in 5th Edition, identical in content to 5th Edition

• ES.next AKA Harmony (6th) Edition is well on its way…– Lots of new stuff

Page 4: JavaScript Enlightenment

4

JavaScript Enlightenment

• JavaScript book by Cody Lindley– http://www.javascriptenlightenment.com/

• Summary of ECMA-262 3rd edition– http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-

262,%203rd%20edition,%20December%201999.pdf

Page 5: JavaScript Enlightenment

5

What's in the book?

"It was my intention to write a book to give the reader an accurate

JavaScript worldview through an examination of native JavaScript

objects and supporting nuances: complex values, primitive values,

scope, inheritance, the head object, etc. I intend this book to be a

short and digestible summary of the ECMA-262, Edition 3

specification, focused on the nature of objects in JavaScript."

- Cody Lindley

Page 6: JavaScript Enlightenment

6

Everything is (acts like) an object// JavaScript only has 6 typesvar pet = {name:'george'}, // Object type = 'monkey', // String age = 5.0, // Number curious = true, // Boolean nothing = null, // Null missing = undefined; // Undefined

// what about Function, Array, Date, RegExp, etc?// they are all just objects...console.log(typeof Array.prototype); // "object"

Page 7: JavaScript Enlightenment

7

Is "function" a JavaScript type?// functions are objects that implement [[call]] --// see prescribed algorithm for the typeof operator:

Page 8: JavaScript Enlightenment

8

Every object has hidden properties

Page 9: JavaScript Enlightenment

9

The [[prototype]] hidden property// a hidden [[prototype]] property is created// automatically and points to the prototype of the// constructor functionvar pet = { name:'george', type:'monkey', description:'curious'};

pet Object.prototype

Page 10: JavaScript Enlightenment

10

Prototype link is fixed// objects do not have a property named prototype,// they have a hidden property called [[prototype]]console.log(pet.prototype) // undefined

// access it through the constructor propertyvar petProto = pet.constructor.prototype;

// you can add a property named prototype, but it// does not change the hidden [[prototype]] linkpet.prototype = {type:'animal'};

Page 11: JavaScript Enlightenment

11

How does the prototype get there?// the hidden prototype link is fixed at the object// construction step – these are the same:var pet = {};var pet = new Object();

// the pet object is constructed with the Object()// constructor function, which does a few things:1. a new empty object is created in memory2. the object gets a hidden link to Object.prototype3. the this keyword in the Object() function points to the new empty object4. Object() function code is executed

Page 12: JavaScript Enlightenment

12

Prescribed construct algorithm// see prescribed algorithm for object construction:

Page 13: JavaScript Enlightenment

13

What does this really do?function Animal() { this.type = 'animal';}

var pet = new Animal();

Page 14: JavaScript Enlightenment

14

Built-in Object Relationships

Object ()

Object.prototype {}

Function ()

Function.prototype ()

[[prototype]]

prototype

Page 15: JavaScript Enlightenment

15

Define a New Constructor Function

Object ()

Object.prototype {}

Function ()

Function.prototype ()

[[prototype]]

prototype

function Animal() { this.type = 'animal';}

Page 16: JavaScript Enlightenment

16

Define a New Constructor Function

Object ()

Object.prototype {}

Function ()

Function.prototype ()

[[prototype]]

prototype

Animal.prototype {}

Animal ()

function Animal() { this.type = 'animal';}

constructor

Page 17: JavaScript Enlightenment

17

Create a New Object

Object ()

Object.prototype {}

Function ()

Function.prototype ()

[[prototype]]

prototype

Animal.prototype {}

Animal () pet {}

var pet = new Animal();

constructor

Page 18: JavaScript Enlightenment

18

Object inheritance using prototypes

// create a named function via a function statementfunction Animal() { this.type = 'animal';}

// Animal automatically gets a prototype propertyconsole.log(typeof Animal.prototype) // 'object'

// pet will have a hidden link to Animal.prototypevar pet = new Animal();

pet{type:'animal'}

Animal.Prototype

Object.prototype

Page 19: JavaScript Enlightenment

19

Functions can be constructors// the this keyword refers to the new objectfunction Animal() { this.type = 'animal';};

// any function can be invoked with the new keyword// to be a constructor (invokes [[construct]])var pet = new Animal();console.log(pet.type); // 'animal'

// No object is created without the new keyword// WARNING: this now references global objectvar pet = Animal(); // pet is undefined

Page 20: JavaScript Enlightenment

20

Constructor function inheritance// will be used as the base constructor functionfunction Animal() { this.type = 'animal';};

// eventually inherit from the base constructor functionfunction Monkey() { this.likesBananas = true;}

// the magic happens here (inheritance) Monkey.prototype = new Animal();

// pet.type will refer to Animal.prototype.typevar pet = new Monkey();

// pet Monkey.prototype Animal.prototype Object.prototype

Page 21: JavaScript Enlightenment

21

Something is wrong!// why does this log Animal? why not Monkey?console.log(pet.constructor);

// the orginal Monkey.prototype was overwrittenMonkey.prototype = new Animal(); // culprit

// the old Monkey.prototype had a property named// constructor – put it back:Monkey.prototype.constructor = Monkey; // fixed

Page 22: JavaScript Enlightenment

22

Neat stuff with functions// start with the original constructor functionfunction Animal() { this.type = 'animal';};

// make the this keyword refer to another objectvar johnathan = {type:'person'}; // random objectconsole.log(johnathan.type); // 'person'

Animal.call(johnathan); // this === johnathanconsole.log(johnathan.type); // 'animal'

Page 23: JavaScript Enlightenment

23

Immediate execution of functions// evaluate a function statement as an expression(function sayHello(name) { alert('Hello ' + (name || 'nobody'));})('George');

// another way to evaluate as an expression!function() { alert('hi'); }();

// parens not necessary for function expressionsvar result = function sayHello(name) { alert('Hello ' + (name || 'nobody'));}('George');

Page 24: JavaScript Enlightenment

24

Function closures// one function returns another functionvar getSecret = function() { // private var var secret = 'JavaScript has private vars';

// this function is closed over outer vars return function() { return secret; };}();

// secret is visible to the inner function after// the outer function has returnedconsole.log(secret); // undefinedconsole.log(getSecret()); // in the circle of trust

Page 25: JavaScript Enlightenment

25

Anonymous function tricks// anonymous functions can call themselves// (won't work in ECMAScript 5+ strict mode)(function(i) { console.log(++i); if (i < 10) { arguments.callee(i); }})(0);

// anonymous functions can be constructors toovar anon = new function() {this.strange = true;}();console.log(anon.strange); // true

Page 26: JavaScript Enlightenment

26

Functions can have properties// count the number of times a function was calledfunction sayHello(name) { console.log('Hello ' + (name || 'nobody')); arguments.callee.numCalls++;}sayHello.numCalls = 0;

// call the function a couple of timessayHello('Curious George');sayHello('Man in the yellow hat');

// numCalls is like a static propertyconsole.log(sayHello.numCalls); // 2

Page 27: JavaScript Enlightenment

27

Why is this stuff important?// understand the libraries you are using(function( window, undefined ) { ... // the entire jQuery library})(window);

// you might need it outside the browser (soon)var http = require('http');http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n');}).listen(1337, "127.0.0.1");

Page 28: JavaScript Enlightenment

28

Summary

• Everything in JavaScript is (acts like) an object• Objects have hidden links to a [[prototype]]• Functions are just "callable objects"• Be careful with semantics– Functions have a hidden [[prototype]] property– Functions also have a visible prototype property

• Pay close attention to scoping– Lexical scoping by default– Scope chain can be modified at runtime

Page 29: JavaScript Enlightenment

29

Questions

?