• Like

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

JavaScript: From the ground up

  • 10,214 views
Uploaded on

An introduction to JavaScript that walks through some of the basics of the languages; types, functions, prototypes, scoping, and then finishes with a look at some interesting libraries.

An introduction to JavaScript that walks through some of the basics of the languages; types, functions, prototypes, scoping, and then finishes with a look at some interesting libraries.

More in: Technology , Business
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
10,214
On Slideshare
0
From Embeds
0
Number of Embeds
9

Actions

Shares
Downloads
304
Comments
7
Likes
32

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • \n
  • \n
  • Image: http://www.flickr.com/photos/ngmmemuda/4166182931/\n
  • \n
  • \n
  • http://www.flickr.com/photos/tomsaint/2988275492/sizes/o/\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • http://www.flickr.com/photos/vegaseddie/3338697679/sizes/o/\n
  • \n
  • \n
  • \n
  • http://www.flickr.com/photos/derricksphotos/209778001/sizes/o/\n
  • \n
  • \n
  • http://www.flickr.com/photos/kwl/4574642827/sizes/o/\n
  • \n
  • http://www.flickr.com/photos/richardmoross/2211308689/sizes/o/\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • http://www.flickr.com/photos/pinguino/2862231080/sizes/o/\n
  • \n
  • \n
  • http://www.flickr.com/photos/thenestor/10934928/sizes/o/\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • http://yuml.me/diagram/scruffy;dir:LR;scale:180;/class/[a3|length] __proto__->[Array|push();pop()], [a2|length] __proto__->[Array], [a1|length]__proto__ ->[Array] \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • http://www.flickr.com/photos/san_drino/1454922072/sizes/l/\n
  • \n
  • \n
  • \n
  • http://www.flickr.com/photos/soldiersmediacenter/4308562661/sizes/o/\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • http://www.flickr.com/photos/yasinhasan/4431896656/\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

Transcript

  • 1. JavaScript: From The Ground UpOr, if you’re a Java or C# Developer writing JavaScript, why you’re probably confused as hell David Padbury http://davidpadbury.com @davidpadbury
  • 2. We
thank
the
following
companies
for
their
gracious
sponsorship Pla6num
Sponsor Gold
Sponsors Silver
Sponsors
  • 3. JavaScript will look familiar to most developers
  • 4. var text = "Barry Manilow Rocks";var words = text.split( );for (var i = 0; i < words.length; i++) { console.log( words[i] );}
  • 5. var barry = new Person(Barry, Manilow);barry.sing();barry.dance();
  • 6. Problem is, it has very little incommon withthe languages it looks like
  • 7. “Java is to JavaScript what Car is to Carpet. “ - Chris Heilmann
  • 8. JavaScript has had a rather messy evolution.
  • 9. Types seem like a good place to start
  • 10. // Booleanvar canSmileWithoutYou = false;// Stringvar name = Lola;// Numbervar yearsAgo = 30;
  • 11. var people = [ mandy, lola, tony ];people[1] = showgirl;console.log( people[1] ); // showgirl
  • 12. var lola = { employer: Copacaba, stuffInHair: [ feathers ]};console.log( lola.stuffInHair )// [ feathers ]
  • 13. var people = [ mandy, lola, tony ];console.log( people[30] ); // undefined// No error
  • 14. null // Value meaning nothingundefined // No valuevar o = { foo: null};console.log( o.foo ); // nullconsole.log( o.bar ); // undefined
  • 15. Comparisons arepretty easy going
  • 16. Truthy orFalsy
  • 17. var emptyString = , // Falsy nonEmptyString = Copa, // Truthy zero = 0, // Falsy nonZero = 42, // Truthy obj = {}, // Truthy nullObj = null, // Falsy undefinedObj; // Falsy
  • 18. if (input != null && input.length != 0) something();// Equivalent to...if (input) something()
  • 19. They can also be a little weird
  • 20. var nullObj = null, undefinedObj; // undefinednullObj == undefinedObj; // True!42 == 42; // True!
  • 21. When you care, be strict about your comparisons var nullObj = null, undefinedObj; nullObj === undefinedObj; // False 42 === 42; // False
  • 22. Functions look pretty traditional at first glance
  • 23. function add(n1, n2) { return n1 + n2;}
  • 24. But what’s cool, is that they’re first class functions
  • 25. var add = function (n1, n2) { return n1 + n2;}
  • 26. Which means you can throw them around
  • 27. function map(arr, fn) { var results = []; for (var i = 0; i < arr.length; i++) { var mapped = fn(arr[i]); results.push(mapped); } return results;}var words = [foo, world];var lengths = map(words, function(word) { return word.length;});console.log(lengths); // [3, 5]
  • 28. function add(n1,n2) { return n1 + n2; }function createAdder(n1) { return function(n2) { add(n1 + n2); }}var oneAdder = createAdder(1);var result = oneAdder(2); // 2 + 1 = 3
  • 29. Functions can get at their arguments as an array
  • 30. function sum() { var total = 0; for (var i = 0; i < arguments.length; i++) { total += arguments[i]; } return total;}sum(1, 2, 3, 4, 5); // 15
  • 31. Objects can bepretty flexible
  • 32. var o = {};console.log( o.name ); // undefinedo.name = Lola;console.log( o.name ); // Lolaconsole.log( o[name] ); // Lola
  • 33. var lola = { employer: Copacaba, stuffInHair: feathers};for (var p in lola) { var value = lola[p]; console.log( p + = + value);}// employer = Copacaba// stuffInHair = feathers
  • 34. Context is important
  • 35. this
  • 36. console.log( this );// In a webbrowser,// by default functions are executed// in the window contextthis === window; // true
  • 37. function constructPerson( name ) { this.name = name;}constructPerson( Lola );this.name === window.name === Lola; // Ooops
  • 38. Just like String has split()Just like Array has slice()Function has methods too
  • 39. function add(n1, n2) { return n1 + n2; }add(2, 3); // Is equivalent too...// call( context, arg1, arg2, argN...)add.call(this, 2, 3);// apply( context, [args] )add.apply(this, [2, 3]);
  • 40. function constructPerson( name ) { this.name = name;}var lola = {};constructPerson.call( lola, Lola );lola.name == ‘Lola’; // True
  • 41. Creating objects with their own state? That seems really useful!If only there was a easier way of doing it....
  • 42. function Person( name ) { this.name = name;}var lola = new Person( Lola );lola.name == Lola; // TRUE!// new short for:// var lola = {};// Person.call(lola);
  • 43. Look familiar?
  • 44. var o = new Object();var a = new Array();var d = new Date();
  • 45. console.log( typeof(Object) ); // Functionconsole.log( typeof(Array) ); // Functionconsole.log( typeof(Date) ); // Function
  • 46. They’re all just functions
  • 47. function Person( name ) { this.name = name; this.sayName = function() { console.log("Hi, Im " + this.name); }}var lola = new Person( Lola );lola.sayName(); // Lola
  • 48. So I know what you’re thinking... Every object has to have it’s owninstances of everything even when they’re all the same? Isn’t that kind of a waste? You were thinking that? Right?
  • 49. JavaScript doesn’t have C#/Java style inheritance
  • 50. It has Prototypes
  • 51. Every object has an associated prototype
  • 52. A prototype is just an object Nothing special
  • 53. When you call something on an objectIt’ll first check all the values on the objectIf it’s not found, it’ll check the prototype That’s it.
  • 54. var a1 = new Array(), a2 = new Array();var proto1 = Object.getPrototypeOf( a1 );var proto2 = Object.getPrototypeOf( a2 );console.log( proto1 == proto2 ); // True
  • 55. var a = [ 1, 2, 3 ];Object.getPrototypeOf( a );a.__proto__;
  • 56. var a1 = [], a2 = [], a3 =[];a1.length;// Selfa1.push( 1 ); // Called on prototype
  • 57. By assigning prototype’s to objects,we can make them behave differently
  • 58. var a = [], o = {};o.__proto__ = a.__proto__;o.push( 30 ); // Suddenly an arrayconsole.log( o ); // [ 30 ]console.log( a ); // []
  • 59. Messing with __proto__ is actually super bad practice So how do we set it?
  • 60. var a = [];// Every function object// has a prototype propertyArray.prototype === a.__proto__; // True
  • 61. var o = {};o.__proto__ = Array.prototype;o.push( 30 ); // Suddenly an arrayconsole.log( o ); // [ 30 ]
  • 62. But how do we set an instance’s prototype without messing with __proto__?
  • 63. var a1 = new Array();a1.__proto__ === Array.prototype;
  • 64. // new is equivalent to...var a1 = {};a1.__proto__ = Array.prototype;Array.call( a1 );
  • 65. Pulling this all together...
  • 66. function Person(name) { this.name = name;}Person.prototype.sayHi = function() { console.log("Hi, Im " + this.name);}var lola = new Person(Lola);var mandy = new Person(Mandy);lola.sayHi(); // Hi, Im Lolamandy.sayHi(); // Hi, Im Mandy
  • 67. So that’s OO in JavaScriptNext up, we have something you probably haven’t thought twice about for a while
  • 68. Scoping It’s again, probably notwhat you expect
  • 69. var n = 1;console.log( n );if (true) { var n = 2; console.log( n );}console.log( n );
  • 70. var n = 1;console.log( n ); // 1if (true) { var n = 2; console.log( n ); // 2}console.log( n ); // 2
  • 71. C like languages typically have block-level scope JavaScript has function-level scope
  • 72. Every declaration in function ishoisted to function wide scope
  • 73. function bar() { if ( false ) { var x = 1; } if ( false ) { var y = 2; }}bar();
  • 74. function bar() { var x, y; if ( false ) { x = 1; } if ( false ) { y = 2; }}bar();
  • 75. var n = 1;function bar() { n = 2; return; var n;}bar();console.log( n ); // 1
  • 76. This is why it’s recommended to only have a single var block at the top of your methods. It’s just what the runtime will do anyway.
  • 77. You know how I said function foo() {} andvar foo = function() {} were the same? I lied.
  • 78. function run() { foo(); // "Foo" - Whole function hoisted bar(); // ERRORZ!!! - Just declaration function foo() { console.log( Foo ); } var bar = function() { console.log( Bar ); }}run();
  • 79. Let’s pull this all together
  • 80. Imagine we combine two JavaScript libraries into a single file. This is a common practice in Web Application.
  • 81. // lib1.jsfunction awesomeFunction() { console.log( lib1 );}// lib2.jsfunction awesomeFunction() { console.log( lib2 );}awesomeFunction(); // lib2
  • 82. We should avoid defining stuff in the global scope We can use function scoping to help us
  • 83. // lib1.js(function(){ function awesomeFunction() { // Doing something awesome... // Honest }})(); // Executed immediately
  • 84. But now we can’t get it at all from other places We can use objects to emulate namespaces
  • 85. // lib1.js(function( lib1 ){ lib1.awesomeFunction() { // Doing something awesome... // Honest }})( window.lib1 || (window.lib1 = {} ) );// All of library isolated to single objectlib1.awesomeFunction();
  • 86. // lib1.js(function( lib1 ) { lib1.awesomeFunction() { console.log( lib1 ); }})( window.lib1 || (window.lib1 = {}) );// lib2.js(function( lib2 ) { lib2.awesomeFunction() { console.log( lib2 ); }})( window.lib2 || (window.lib2 = {}) );lib1.awesomeFunction(); // lib1lib2.awesomeFunction(); // lib2
  • 87. DemoMaking some of this stuff real
  • 88. So that’s pretty much JavaScript
  • 89. Hang about.We went an entire JavaScript talkwithout once mentioning jQuery?
  • 90. Yep. jQuery is great for dealing withbrowsers and for messing with the DOM tree.
  • 91. But it doesn’t help us write large JavaScript applications.
  • 92. Challenges facing JavaScript today...
  • 93. Organizing Code Expressing Dependencies Intelligent Build Tools Application StructureDealing with Progressive Enhancement
  • 94. Until these things improveWriting large JavaScript applications is difficult But not impossible
  • 95. Fortunately, things are improving at an immense pace.
  • 96. Jasmine BDD RSpec like BDD for JavaScriptdescribe(Calculator, function() { var counter = 0; it(can add a number, function() { counter = counter + 2; expect( counter ).toEqual( 2 ); });});
  • 97. Dojo Expressing dependencies for packaging// myApp/base.jsdojo.provide(myApp.base);dojo.require(myApp.Settings);dojo.require(myApp.SomethingElse); Rebecca Murphey - Scaffolding a buildable dojo application
  • 98. Knockout.js MVVM for JavaScript// html<select data-bind="options: availableMeals, optionsText: name, value: chosenMeal"></select>// jsvar viewModel = { availableMeals: [ { name: Chicken }, { name: Pasta} ], chosenMeal: ko.observable()};ko.applyBindings(viewModel);
  • 99. Node.js JavaScript in your backendvar http = require(http);http.createServer(function (req, res) { res.writeHead(200, { Content-Type: text/plain }); res.end(Hello Worldn);}).listen(8124, "127.0.0.1"); Come back later for more of this...
  • 100. Coffee Script A little language that compiles into JavaScript# Conditions:number = -42 if opposite# Functions:square = (x) -> x * x# Objects:math = root: Math.sqrt square: square cube: (x) -> x * square x# Existence:alert "#{elvis} is alive!" if elvis?# Array comprehensions:cubes = math.cube num for num in list
  • 101. Questions?
  • 102. http://www.lab49.com New York .NET Meetuphttp://www.meetup.com/NY-Dotnet
  • 103. // Thanks for listening!return;
  • 104. Scoping and Hoisting, Ben Cherry - http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-HoistingPrototypes and Inheritance, Scott Allen - http://msdn.microsoft.com/en-us/scriptjunkie/ff852808.aspxGreat content on challenges building JS applications, Rebecca Murphey - http://blog.rebeccamurphey.com/WTF JS - http://wtfjs.com
  • 105. Good Friends - Juliana Coutinho, http://www.flickr.com/photos/ngmmemuda/4166182931/Skeleton Jack-O-Lantern - Rennett Stowe, http://www.flickr.com/photos/tomsaint/2988275492/Evolution - spaceamoeba, http://www.flickr.com/photos/spaceamoeba/3101102763/Orangutan Relaxing - Paolo Camera, http://www.flickr.com/photos/vegaseddie/3338697679/The Sophistication of Mr. Lamp-shade - DerrickT, http://www.flickr.com/photos/derricksphotos/209778001/careful now - Abulic Monkey, http://www.flickr.com/photos/abulic_monkey/135488031/sThe Simple Life - kennymatic, http://www.flickr.com/photos/kwl/4574642827Thai First Class Seat (1A) - Richard Moross, http://www.flickr.com/photos/richardmoross/2211308689/contortionist - pinguino, http://www.flickr.com/photos/pinguino/2862231080/out of context, this is naughty - David Nestor, http://www.flickr.com/photos/thenestor/10934928/What is going on? - SAN_DRINO, http://www.flickr.com/photos/san_drino/1454922072/Hoist training exercise in Irqa - The U.S. Army, http://www.flickr.com/photos/soldiersmediacenter/4308562661/Sunday means get together - Yasin Hassan, http://www.flickr.com/photos/yasinhasan/4431896656/Colbert image used with absolutely no permission at all - Sorry, http://blog.quickdfw.com/archives/2007/01/hell-beg-to-differ.html