<<

The JavaScript Language Chris Morgan North Texas PC Users Group June 2010 Background

• JavaScript originated in 1995 by Netscape • Microsoft version was called Jscript • Standardization happened in 1998 – called ECMAScript • WikiPedia: “JavaScript is a dialect of the ECMAScript standard and is characterized as a dynamic, weakly-typed, prototype-based language with first-class functions.” Basics

• JavaScript is a true object-oriented language • JavaScript has no “classes”, like in # or Java • A JavaScript object is a collection of name/value pairs called “properties” (an “”) • Supports arrays and functions • Arrays can have values of different “types”, including functions • Functions are objects • Case-sensitive language • Lines end with a semi-colon • Variables are loosely typed – inferred at runtime • All data types are objects Objects

• var book = new Object(); • var book = {}; • {} represents an “empty” object • Once created, objects can be expanded at any time, by adding properties on the fly • book.title = “jQuery In Action” • Creates the property “title” • Assigns a value to this new property • Can be anywhere in the code, executed at any time • for(var prop in book){alert(“Name: ” + prop + “, “Value: ” + book[prop])}; • Property values of objects also have implied properties and methods JavaScript Data Types

• Number • String • Date • Boolean • Math • Array • RegExp • Function String Object

• var txt = new String(string); or • var txt = string; • Implied properties • Length • Implied methods • HTML: bold() big() fixed() fontcolor() fontsize() italics() link(url) small() strike() sub() sup() sub() • Object: charAt() concat(str2, str3, …) indexOf() lastIndexOf() match() replace() search() sliced() split() substring() substr() toLowerCase() toUpperCase() Other Data Types

• var num = new Number(6.3); • var num = 6.3; • Implied methods: • toString() • toFixed(x) • toPrecision(x) • toExponential() • var = new Date() • var b = new Boolean() Arrays

• A JavaScript array is an ordered collection of values that can be of different types • var arr = new Array(); • var arr = []; • Similar to generic lists in .NET • New array elements can be added at any time • Array elements can be strings, numbers, dates, booleans, objects, functions, and child arrays • No space is pre-allocated for array elements JavaScript Functions • Treated as an object – a “first-class function” • Functions can be instantiated (created), returned by other functions, stored as an array element or object property, or assigned to a variable • Normal declaration of a function: function myFunc(parm1, parm2) { parm1 = parm1 + parm2; return parm1; } • A function with no paramters still uses the parentheses function myFunc() {return “Some Text”;}; • Defines an object “calc”: var calc {}; • Adds a function property to the object just created; a method: calc.add = function(a,b){return (a + b)}; • Use of the function: var c = calc.add(2,3); • A JavaScript function stored as an object property is called a “method” • Functions can be nested JavaScript Functions

• All functions are executed as a method of some object • The ‘this’ keyword is a reference to the object which is executing the method • 1) Global object is ‘this’ when function is defined in the page as a global function • 2) DOM Event Handler – ‘this’ references the DOM element that hooked up the • If you are in an HTML element nested in another element having an event and you click on the inner element, the click event will “bubble” up to the outer element that subscribed to the event and fire off. ‘this’ will refer to the outer element, not the element which triggered the event. • 3) Constructor function – ‘this’ refers to the object being created • Properties of objects cannotbe private in . JavaScript Functions

• Anonymous functions • You can define and use a function without giving it a name. Use the keyword ‘function’ instead of a name. • Example: you can assign a function to a variable and execute this variable like a function: var myFunc = function(parm1, parm2){parm1 = parm1 + parm2; return parm1;} • Example: when you are assigning a function to a ‘click’ event, you can just define the function there instead of referencing one that was already declared • Closure • When functions, variables declared in an outer function can be seen by the inner functions JavaScript Functions

• You can assign a function to a variable or an object property – a pointer – and use the pointer just like the function. So, you can have multiple ways to execute the same function. If the function changes, then all the pointers (variables) have the new functionality. var c; function myFunc(p1, p2){return p1 + p2}; var abc = myFunc; c = abc(“Hello”, “World”);

• Since a function is an object, you can create properties for it. Javascript - first class functions

functional programing style Javascript: • supports passing functions as arguments to other functions, • returning them as the values from other functions, • assigning them to variables • storing them in data structures • supports for anonymous functions (function literals)

The names of functions do not have any special status; they are trated like ordinary variables with a function type Javascript closure (1) – var access in functions

local access - inside global access – outside

JavaScriptvariables can belong to the local or global scope. Global variables can be made local (private) with closures. Javascript closure (2) – counter dilemma Javascript closure (3) – nested function

private variable

self-invoking function (immediately-invoked function expressions)

nested function closure

A closure is a function having access to the parent scope, even after the parent function has closed. Javascript module pattern (1) – anonymous closure

(function () {

// ... all vars and functions are in this scope only // still maintains access to all globals

}());

the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application Javascript module pattern (2) Internal state var MyModule = (function () { var my = {}, private method privateVariable = 1; global var function privateMethod() { // ... } property

my.moduleProperty = 1; my.moduleMethod = function () { // ... }; method

return my; }()); return value Javascript – prototype

• A prototypeis a working object instance.

• Objects inherit directly from other objects.

• Javascriptfavor over class inheritance. Javascript – prototypal inheritance • Prototypedelegation - an object may have a link to a prototypefor delegation. If a property is not found on the object, the lookup is delegated to the delegate prototype, which may have a link to its own delegate prototype, and so on up the chain until youarrive at `Object.prototype`, which is the root delegate.

• Concatenative inheritance - The process of inheriting features directly from one object to another by copying the source objects properties. In JavaScript, source prototypes are commonly referred to as mixins.

• Functional inheritance- any function can create an object. When that function is not a constructor(or `class`), it’s called a factory function. Functional inheritance works by producing an object from a factory, and extending the produced object by assigning properties to it directly (using concatenative inheritance). Javascript – example (1)

Javascript – example (2) Javascript – example (3)

arguments – special var

variadic function Javascript – example (4) – this