• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JavaScript Growing Up
 

JavaScript Growing Up

on

  • 6,119 views

 

Statistics

Views

Total Views
6,119
Views on SlideShare
6,110
Embed Views
9

Actions

Likes
9
Downloads
69
Comments
0

4 Embeds 9

https://twitter.com 4
http://twitter.com 2
http://portal.accelrys.net 2
https://si0.twimg.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

JavaScript Growing Up JavaScript Growing Up Presentation Transcript

  • JavaScript Growing Up Modules, Platform Consistency and Harmony David Padbury
  • Between HTML5 and Node, JavaScriptis seeing a staggering level of adoption.
  • The patterns and tools and practices that will form the foundation of Modern JavaScript are going tohave to come from outside implementations of the language itself - Rebecca Murphey
  • Modules
  • Java has importC# has using JavaScript has? Nothing.
  • So JavaScript authors used what we had inthe language to provide what we needed.
  • But before we get to that, first some prerequisites.
  • Everything is global// lib1.jsvar name = Barry;function sayHi() { alert("Hi, Im " + name);}<script src="lib1.js"></script><script> something(); console.log(name); // Barry</script>
  • Which could make including multiple libraries challenging // lib1.js function something() { console.log(foo); } // lib2.js function something() { console.log(bar); } <script src="lib1.js"></script> <script src="lib2.js"></script> <script> something(); </script>
  • Using simple JavaScript constructs we can emulate many traditional organization techniques ;(function(lib1) { lib1.something = function() { ... }; })(window.lib1 = window.lib1 || {}); lib1.something(); lib2.something();
  • function namespace(ns) { var obj = window; ns.split(.).forEach(function(component) { obj = typeof obj[component] !== undefined ? obj[component] : obj[component] = {}; }); return obj;}
  • (function(data) { data.something = function() { ... };})(namespace(lab49.app.data));
  • (function(example) { function privateAdd(num1, num2) { return num1 + num2; } example.add = function(num1, num2) { return privateAdd(num1, num2); };})(namespace(lab49.example));console.log(typeof example.add); // functionconsole.log(typeof example.privateAdd); // undefinedconsole.log(typeof privateAdd); // undefined
  • Server-side JavaScript authors started to talk aboutwhat a more robust module system would look like.
  • I generally support the CommonJS idea, but let’sbe clear: it’s hardly a specification handed down bythe gods (like ES5); it’s just some people discussing ideas on a mailing list. Most of these ideas are without actual implementations. - Ryan Dahl (creator of node.js)
  • Introduced a simple API for dealing with modules. require for importing a module. exports for exposing stuff from a module. http://wiki.commonjs.org/wiki/Modules/1.1.1
  • // math.jsexports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum;};//increment.jsvar add = require(math).add;exports.increment = function(val) { return add(val, 1);};// program.jsvar inc = require(increment).increment;var a = 1;inc(a); // 2
  • CommonJS modules are now the de-facto for server based JavaScript.
  • var http = require(http);var server = http.createServer(function(req, res) { res.writeHead(200, { Content-Type: text/plain }); res.end(Hi Lab!);});
  • There are now a number of tools to bring CommonJS modules to the browser. https://github.com/substack/node-browserify https://github.com/sstephenson/stitch
  • var stitch = require(stitch);var express = require(express);var package = stitch.createPackage({ paths: [__dirname + /lib, __dirname + /vendor]});var app = express.createServer();app.get(/application.js, package.createServer());app.listen(3000);
  • There are some problems with using this module format in the browser.
  • Asynchronous Module Definition (Commonly known as AMD) https://github.com/amdjs/amdjs-api/wiki/AMD
  • define for creating a module definition.
  • define(personView, [models/person], function(person) { return { initialize: function() { ... } };});
  • AMD is now used by RequireJS, Dojo and even Node.
  • RequireJS also supports text templates.
  • Becoming the most common way to structure large JavaScript applications, both on the server and in the browser.
  • JS.next will be introducing language level modules.These are similar to the modules we’ve been looking at.
  • module Math { export function add(x, y) { return x + y; }}Math.add(2, 2);import Math.*;add(2,2);
  • But not much implements that yet. Why do we care? I’ll get to that later.
  • Platform Consistency
  • Everyone knows that the biggest suckage in modern JavaScript is dealing with different platforms.
  • PolyfillA shim that mimics a future API, providing fallback functionality to older browsers. http://stateofhtml5.appspot.com/
  • You can fake a surprising amount now days.
  • ;(function(geolocation){ if (geolocation) return; var cache; geolocation = window.navigator.geolocation = {}; geolocation.getCurrentPosition = function(callback){ if (cache) callback(cache); $.getScript(//www.google.com/jsapi,function(){ cache = { coords : { "latitude": google.loader.ClientLocation.latitude, "longitude": google.loader.ClientLocation.longitude } }; callback(cache); }); }; geolocation.watchPosition = geolocation.getCurrentPosition;})(navigator.geolocation);
  • border-radius: 8px;box-shadow: #666 0px 2px 3px;background: linear-gradient(#eeff99, #66ee33);behavior: url(/PIE.htc); http://css3pie.com/
  • But just because you can,it doesn’t mean that you should.
  • But if we are in different environments,we can start with some polyfills that are much simpler.
  • Array.prototype.forEachArray.prototype.mapArray.prototype.filterArray.prototype.everyArray.prototype.someArray.prototype.reduceArray.prototype.indexOfObject.keysDate.nowDate.prototype.toISOStringFunction.prototype.bindString.prototype.trim
  • [one, two, three].map(function(word) { return word.length}).filter(function(length) { return length > 3;});
  • It is not seldom that you see people messing withObject.prototype.This is very bad because it breaks the object-as-hash-tables feature in javascript. Array.prototype.map = function() {...}; var arr = [1,2,3]; for (var p in arr) { console.log(p); } // 1 // 2 // 3 // map - erm, what?http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/
  • Array.prototype.map = function() {...};var arr = [1,2,3];for (var p in arr) { if (arr.hasOwnProperty(p)) { console.log(p); }}
  • So where we can polyfill basic language functionality, take advantage of it. https://github.com/kriskowal/es5-shim
  • Harmony
  • JavaScript is the x86 of the web - Brendan Eich (creator of JavaScript)
  • Google Traceur - JavaScript to JavaScript Compiler http://code.google.com/p/traceur-compiler/
  • Harmony Features Modules Iterators Iterators and For Each Generators Block Scoped Bindings Destructuring Assignment Default Parameters Rest Parameters Spread Operator Strawman Features Classes Traits Deferred Functions Object Initializer Shorthandhttp://code.google.com/p/traceur-compiler/wiki/LanguageFeatures
  • Destructuring Assignmentvar [a, [b], c] = [hello, [, , junk], world];alert(a + b + c); // hello, world http://traceur-testbed.herokuapp.com/destructuringArrayAssignment var pt = { x: 23, y: 42 }; var {x, y} = pt; console.log(x); // 23 http://traceur-testbed.herokuapp.com/destructuringObjectAssignment
  • function slice(list, start = 0, end = list.length) { ...} http://traceur-testbed.herokuapp.com/defaultParameters
  • function print(...items) { items.forEach(function(item, index) { console.log(index, item); });}print(foo, bar);// 0, foo// 1, bar http://traceur-testbed.herokuapp.com/restParameters
  • var a1 = [1,2,3], a2 = [];a2.push(...a1);// a1.push.apply(a1, a2) http://traceur-testbed.herokuapp.com/spreadOperator
  • Deferred / Promisesvar deferred = $.Deferred();// or dojo.Deferred, new Deferred(), etc...// Complete the deferreddeferred.resolve(...args);// Fail the deferreddeferred.reject(...args);// Return a read-only deferreddeferred.promise();// Attach handlers for when resolve or rejecteddeferred.then(function(...args) { ... }, function(...args) {...}); http://wiki.commonjs.org/wiki/Promises
  • function wait(duration) { var deferred = $.Deferred(); window.setTimeout(function() { deferred.resolve(); }); return deferred.promise();}wait(1000).then(function() { alert(done);});
  • function deferredWait(timeout) { var d = $.Deferred(); window.setTimeout(function() { d.resolve(); }, timeout); return d;}function waitOnThings() { alert(Starting); await deferredWait(1000); alert(Finished);} http://traceur-testbed.herokuapp.com/await
  • Thanks for listening!