The JavaScript  Programming Primer
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

The JavaScript Programming Primer

on

  • 5,190 views

JavaScript Language Overview

JavaScript Language Overview

Statistics

Views

Total Views
5,190
Views on SlideShare
5,050
Embed Views
140

Actions

Likes
9
Downloads
154
Comments
0

7 Embeds 140

http://www.genes.com 54
http://www.redditmedia.com 34
http://clubajax.org 32
http://www.slideshare.net 12
http://www.linkedin.com 5
http://localhost 2
https://www.linkedin.com 1
More...

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
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />
  • <br />

The JavaScript Programming Primer Presentation Transcript

  • 1. The JavaScript Programming Primer Scope Context Closures Presentation by Mike Wilcox February 3rd, 2009
  • 2. Overview ★ JavaScript Language Overview ★ Object ★ Array ★ Function ★ Scope ★ Context ★ Closures
  • 3. Is JavaScript Easy? ★ Scripting languages often considered simple ★ Loose Typing makes it versatile and extremely flexible ★ Functional style allows quick tasks: myDiv.hide(); image.swap(); myForm.validate(); // with script I found on the Internet
  • 4. It is not a Toy! ★ Interpreted language not compiled ★ Loosely Typed ★ OO capabilities ★ Resembles C, C++ and Java in some syntax only ★ Uses prototype for inheritance like Self
  • 5. Mutable All JavaScript objects, including the native objects, can be added to or extended String.prototype.reverse = function(){ return this.split("").reverse().join(""); } var a = "Club Ajax"; console.log(a.reverse()); // xajA bulC
  • 6. Mutable So exactly how “mutable” is JavaScript anyway? Array = function(){ alert("JavaScript no longer has Arrays."); } var a = new Array("club", "ajax");
  • 7. Object
  • 8. Object Defined A JavaScript object is a composite datatype containing an unordered collection of variables and methods. ★ All objects are a hash map and everything is an object ★ All JavaScript objects are mutable - even the built in methods and properties can be changed. ★ An object variable is a property - like a field in Java ★ Can contain any type of data - even functions
  • 9. Object Definitions Creating an object by Definition, using the object’s constructor function obj = new Object(); obj.prop = "Club AJAX" obj.subObj = new Object(); obj.subObj.location = “Dallas”; obj.subObj.when = new Date("2/3/2009");
  • 10. Object Literals Creating an object with the Literal syntax - also known as an initializer name = {prefix:"Club", suffix:"AJAX"}; obj = { fullname: name.prefix + name.suffix, deep:{ fullname: name.prefix + “ “ + name.suffix } };
  • 11. Object - Value Access // dot syntax image.width; image.height; obj.myDomElement; obj.myFunction; obj.myArray; // associative array obj["myDomElement"]; obj["myFunction"]; obj["myArray"]; var i = “myArray”; obj["myArray"] = obj["my” + ”Array"] = obj[i] = obj.myArray;
  • 12. Array
  • 13. Array in Brief ★ An untyped, ordered object ★ Has a length property ★ Additional methods: push(), pop(), etc. // Definition var a = new Array(10); // sets length var b = new Array(“club”, “ajax”); // sets array // Literal var c = ["club", "ajax"]; c[2] = "rocks"; // Bad form! myArray["prop"] = "associative"; // works but unexpected
  • 14. Function
  • 15. Functions Unlike Java, Functions are literal data values that can be manipulated. They can be assigned to variables, properties of objects, the elements of an array, or passed as arguments.* ★ Concept borrowed from Lisp Lambda functions ★ Functions are first class objects ★ Functions are objects with executable code ★ Can be used as constructors for object instances** ★ Used as a literal or a definition * JavaScript - The Definitive Guide ** Function constructors will be covered in the presentation about Inheritance.
  • 16. Function Definition Function Definition created by the function keyword: function ninja(){ return "ninja"; }
  • 17. Function Literal ★ An expression that defines an unnamed function ★ Also called Function Statement or an Anonymous Function or a Function Expression ★ Much more flexible than Definitions, as they can used once and need not be named* // Unnamed Function assigned to "foo": f[0] = function(x){ return x * x;} myArray.sort(function(a,b){ return a<b; }); var squared = (function(n){ return n*n })(num); *JavaScript the Definitive Guide
  • 18. Function Literal Usage // Stored as a variable: ar[1] = function(x){ return x * x; } ar[1](2); // 4 // Passed as an argument: var add = function( a, b ){ return a() + b(); } add(function(){ return 1; }, function(){ return 2; }); // 3 // Invoked Directly: var foo = (function(){ return "bar"; })(); // foo = "bar", the result of the invoked function, // not the function itself
  • 19. Assigning a Literal to Definition Allows the body of the function to refer to the Literal var f = function factor(x, num){ if(x==0){ return num; }else{ return factor(x-1, num+=x) } } console.log(f(3, 0)); // 6 console.log(factor(3, 0)); // ERROR factor is undefined
  • 20. Function as a Method A function can be added to any object at any time var dimensions = {width: 10, height: 5}; dimensions.getArea = function() {   return this.width * this.height; }
  • 21. Scope
  • 22. Scope ★ Scope is an enclosing context where values and expressions are associated and is used to define the visibility and reach of information hiding* ★ JavaScript uses a lexical (or static) scope scheme, meaning that the scope is created and variables are bound when the code is defined, not when executed http://en.wikipedia.org/wiki/Scope_(programming)
  • 23. Scope - Simple Example ★ Functions can see the scope outside them, but not inside of them var assassin = "Ninja"; function getWarrior(){ alert(assassin); // SUCCESS! } function setWarrior(){ var warrior = "Ninja"; } alert(warrior); // FAILS!
  • 24. Scope Diagram The scope chain resembles a hierarchal tree, much like that of classical inheritance scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope
  • 25. Scope Diagram Like classical inheritance, the children can see their ancestors, but parents scope cannot see their descendants scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope
  • 26. Scope Diagram scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope scope
  • 27. Scope - Objects ★ Objects don’t create a scope (they create context), but they are able to access scope: var first = “kick”; var myObject = { type:first, // scope captured here attack: function(){ return this.type; } } alert(myObject.attack());
  • 28. Scope - No Blocks No block-level scope, unlike C, C++, and Java function scoping(){ var a = 1; for(var i=0, len=20; i < len; i++){ if(i==10){ var b = i; break; } } while(b<20){ b++; } console.log(a + i + len + b); // 51 - no errors, all defined }
  • 29. Scope - Activation Variables declared within a function are defined throughout the function var hero = "Spider-man" function scoping(){ alert(hero); // - output ? var hero = "Dr. Octopus"; alert(hero); // - output ? }
  • 30. Hey what is var anyway? The var statement defines a variable by creating a property with that name in the body of an enclosing function. If the declaration is not within a function body, it is declared in the global scope.* var i; var x = 10; var w = 20, y = 30, h = 100; var f = function(arg){ var a = 1; var arg = arg + 1; // - result ? } *JavaScript the Definitive guide
  • 31. Scope Global ★ In a browser, the window is global ★ Global scope is special because it is the end of the scope chain, and since it is an object, it has context ★ The following all mean the same thing, in the global scope only: <script> window.weapon = "katana"; weapon = "katana"; var weapon = "katana"; this.weapon = "katana"; </script>
  • 32. Scope Accidental Globals Regardless of the depth of the scope, not using var always assigns the variable as a global transportation = “horse”; alert("Ninja rides a:", transportation); // - output ? function ride(){ transportation = "Kawasaki"; alert("Ninja rides a:", transportation); // - ? } alert("Ninja rides a:", transportation); // - output ?
  • 33. Context
  • 34. Context ★ Context is a method’s reference to an object ★ A function and a method are different! ★ A method has context to the object to which it belongs (a function does not) ★ Whereas scope is lexical and can be determined by the program code, context is executional, and is determined at runtime ★ Tip: scope belongs to functions, and context belongs to objects
  • 35. Context - this ★ A method has a very important keyword: this ★ A method’s value of this becomes the object that invoked it ★ Context can be thought of as this* ★ this cannot be explicitly set, but it can be changed ★ Change this with either call() or apply() ★ JavaScript libraries usually have convenience functions to change this *Execution context actually has a broader meaning that includes scope, which is an advanced topic.
  • 36. Context vs Scope ★ Context refers to an object and its properties and methods ★ Scope refers to local functions and variables, irrespective of the object or its context var myObject = { init: function(){ this.myProperty = “prop”; this.myMethod = function(){ ... } var myVariable = “value”; var myFunction = function(){ ... } } }
  • 37. Context - Example var attire = { ring:"shobo", init = function(){ return this.ring; } } attire.init(); // context of attire applied to init()
  • 38. "this" is confusing! If context is not set, regardless of scope, this will default to the global object function testNoContext(){ var location = "here"; // local variable, not a context property alert(this.location); // returns the window.location object } function testNoContext(){ locashion = "TYPO"; alert(location); // returns the window.location object }
  • 39. Context - Maintaining When one object calls another, it can sometimes be confusing to know in which context you are var a = { objectId: "A", doCall: function(){ return this.objectId; } }; var b = { objectId: "B", callOther: function(){ return a.doCall(); } }; alert(b.callOther()); // - result ?
  • 40. Context - Maintaining Using call() gets a different result var a = { objectId: "A", doCall: function(){ return this.objectId; } }; var b = { objectId: "B", callOther: function(){ return a.doCall.call(a); } }; alert(b.callOther()); // - result ?
  • 41. Context - Changing Context often "fixed" in "functions" with this pattern: var self = this; var myFunc = function(){ self.doMethod(); } myFunc();
  • 42. dojo.hitch dojo.hitch changes context for you, using apply() in the background myFunc = function(){ this.doMethod(); } dojo.hitch(this, myFunc)(); // or: myFunc = dojo.hitch(this, function(){ this.doMethod(); });
  • 43. Context - setTimeout setTimeout is often awkward due to context. dojo.hitch fixes this: setTimeout(dojo.hitch(this, function(){ this.battle = this.doEvil + this.doGood; this.getConflicted(); }), 500);
  • 44. Context - Anonymous Functions desc var o = { objectId: "A", docall:function(){ alert(this.objectId); }, init: function(){ var callCall = dojo.hitch(this, function(){ this.docall(); }); var cc = function(){ this.docall(); } callCall(); // - result ? dojo.hitch(this, cc)(); // - result ? cc.call(this); // - result ? } }
  • 45. Closures
  • 46. Closures ★ By definition, closures operate in the execution context and are a combination of scope and code ★ The result of invoking a function that captures a variable outside of its scope ★ Closures are not bad - they are quite powerful ★ However: ★ They can consume more memory ★ Creating a circular reference with a DOM node in IE is what causes memory leaks
  • 47. Closures - Simple Example saveForLater = function(){ var weapon = “throwing stars”; return function(){ return weapon; // captures ‘a’ } } var device = saveForLater(); // - result ? setTimeout(function(){ alert(device()); // - result ? }, 1000); var doItNow = saveForLater()(); // - result ?
  • 48. Closures - Private Variables var count = new (function(){ var num = 0; return function() { return num++ } })(); alert(count()); alert(count()); alert(count());
  • 49. Memory Leak Example The onclick function creates a scope and captures the node variable. The GC can’t remove node because it is used by onclick, and it can’t remove the DOM element because the node variable refers to it. function attach(){ var node = document.createElement("div"); node.onclick = function(){ alert("clicked" + node); } }
  • 50. Memory Leak Fixed The following shows how to do your own GC chores. Note that most JavaScript libraries will handle this for you in the background. function attach(){ var node = document.createElement("div"); node.onclick = function(){ alert("clicked" + node); } window.onunload = function(){ node.onclick = null; window.onunload = null; } }
  • 51. dojo.connect dojo.connect is specifically designed for preventing for preventing memory leaks var doClick = function(event){ if(event.type==”onclick”){ alert(“clicked”); } } var node = document.createElement("div"); var ref = dojo.connect(node, “click”, window, doClick); // when window unloads, dojo will disconnect: dojo.disconnect(ref);
  • 52. References JavaScript Closures - Jim Ley http://www.jibbering.com/faq/faq_notes/closures.html#clIRExSc Lexical Scoping http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx Closures and IE Circular References - Scott Isaacs http://siteexperts.spaces.live.com/Blog/cns!1pNcL8JwTfkkjv4gg6LkVCpw!338.entry kartikbansal http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx WikiPedia http://en.wikipedia.org/wiki/Scope_(programming) Mozilla JavaScript Spec http://www.mozilla.org/js/language/E262-3.pdfs JavaScript - The Definitive Guide by David Flanagan