Copyright By wangyoutian@nilnul.com Free for non-commercial use. Editable provided that the copyright claim is included. Notational Conventions For Heading Slides: Background Hue: Red, Yellow, Green, Cyan, Blue, Magenta as in Iris Saturation decreases Brightness increases Color offset to Background Font size decreases Position Shifted right Sideline slides are grey Notational Conventions Unordered List Bullets Ordered by color and the bigness of colored area Font size decreases The most worth-learning language Contents Intro Values Types Literal Var Function Call Expression Statements objects Closure regex An Example <html> <head> <script type="text/javascript"> function displayDate() { document.getElementById(“demo”).innerHTML=Date(); } </script> </head> <body> <h1>My First Web Page</h1> <p id=“demo”>This is a paragraph.</p> <button type=“button” onclick=“displayDate()”>Display Date</button> </body> </html> The History Of ES NetScape liveScript javaScript Not Java ECMA The Script JavaScript VBScript IDE Notepad Visual Studio … DreamWeaver ECMAScript in HTML <script> </script> <script src=“.js”></script> Not <script src=“.js”/> Location in head <html> <head> <!—loaded before page loading--> <script type="text/javascript“> function displayDate(){ document.getElementById("demo").innerHTML=Date(); } < /script> < /head> <body> <h1>My First Web Page</h1> <p id="demo"></p> <button type="button" Date</button> </body> < /html> onclick="displayDate()">Display Location in body <html> < body> <h1>My First Web Page</h1> <p id="demo"></p> <script type="text/javascript"> document.getElementById("demo").innerHTML=Date(); < /script> </body> < /html> <!--Note that the JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created.--> Multiple Locations unlimited number of scripts in your document in both the body and the head section at the same time. Location Matters For browser not supporting ES Browsers that do not support JavaScript, will display JavaScript as page content. The content is commented so that nothing is displayed. <html> <body> <script type="text/javascript"> < !— document.getElementById("demo").innerHTML=Date(); //--> </script> The two forward slashes at the end </body> of comment line (//) is the < /html> JavaScript comment symbol. This prevents JavaScript from executing the --> tag. Literals, Constants/Variables, Expressions And their types, scopes, etc Values Language Types primitive Undefined Null Boolean Number String Object Function Array typeof () typeof(expr) typeof expr returns a string Lowercase boolean string number undefined object function typeof null; //object typeof (function(){}) Undefined Value: undefined alert(undefined); //undefined alert(window.b); //undefined alert(a); //nothing, maybe err alert(1); //nothing ‘cuz prvious err Null Value: null typeof null; // in IE, object! Bool true false Number 64-bit +0,-0 Infinity +Infinity -Infinity NaN String “string” ‘’ Escape \” \’ \\ \t \n \f new – function as Constructor {name:value} {“name”:value} object the type Object alert([{},{i:1}); //[object Object],[object Object] alert([new Date(),typeof new Date()]); //date in string, object alert([Math,typeof Math, Math.constructor,Math.prototype]}; //[object Math],object,function (){[native code]},object Math alert(window); //[object] Property Attributes Data Property Attributes [[Value]] [[Writable]] [[Enumerable]] [[Configurable]] Accessor Property Attributes Get Set Configurable Enumerable internal Internal Property delete {}.name; alert(); delete window.alert Array alert([ [],typeof [] ]); //,object //note [] is empty concat-ed alert([ new Array(),typeof new Array() ]) //, object alert([ Array(), typeof Array() ]); //,object Array as object //{[[Class]]:”Array”, 0:…,1:…,} [1,”a”][3]; //undefined Function function(){} function(x,y){return x+y;} … function as val alert(function(){}); alert(typeof(function{})); var a=function(){}; //function function as object //{[[Call]] :function(){},[[Class]]:”Function”, ……} function(){}.name; function(){}.name=“1”; var a=function(){}; a.name=“1”; alert(a); alert(a.name); Var name Variable names must begin with a letter or the underscore character _1, _a_, _, __ $ These are wrong: 1, 2a, A-b Var declaration Declare a var var a; A var can be used without declaration Var type and value Weak type. The type of var is mutable A=1;A=“hello”; Scope of Var declared within a function can only be accessed within that function. Local variables are destroyed when you exit the function. can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. declared outside a function; – If you declare a variable, without using "var", the variable always becomes GLOBAL. • all scripts and functions on the web page can access. • destroyed when you close the page. Global scope can be regarded as within a virtual global func. var a=1; alert(window.a); //1 //window.a=undefined; delete (window.a); alert(a); //undefined function [[Call]] function has an internal [[Call]] property. To call a function funcName(a1,a2,…); Parameter/arguments (function (x0,x1){ alert(x0); alert( [ arguments[1],arguments[2] ] ); })(1); //1//undefined Operator +-*/% on number,+ on string If you add a number and a string, the result will be a string! ==,!=,>,<,>=,<=,===,!== &&,||,! &,|,^,~,>>,<<,>>> Bool?obj:obj , , expr1,expr2 //expr2 expr1,expr2,expr3 (expr1,expr2),expr3 alert((1, 2)); //2 alert((1,2,3));//3 alert(1, 2); //1 //expr3 == Ref, pointing to the same obj Val, alert([] == []);//false alert(1==1); //true; alert(“”==“”); //true void-operator void void 1; void (1); void(1); Expressions Operator can be regarded as func. Expr is a func call. E.g 1+1 a=1 1+a typeof(a)+””; Statements Case sensitive Semicolon Using semicolons makes it possible to write multiple statements on one line. JavaScript code (or just JavaScript) sequence of JavaScript statements. Blocks {} is a Comment // //comment var a=1; //coment /* */ var a=1; /*coment*/ var a /*comment*/ =1; var a=1;/*coment and Comment*/ Using Comments to Prevent Execution Var declaration and assignment var a=1; =,[+-*/%]=,++,--,+=on string Function declaration var a=function(){}; function a(){}; Operator-Statements if(){} else{} Switch Switch (aVar){ Case 1: … Break; Case “”: … Break; Default: … Break; } Use break to prevent the code from running into the next case automatically. For for(;;){ break; continue; } While/Do/In While(){break;continue;} Do{}while() for(var in collection){} return return ; return { }; //not return // {} label Outer: for (i = 1; i <= 10; i++) { document.write ("<br />"); document.write ("i: " + i); document.write (" j: "); Inner: for (j = 21; j <= 30; j++) { if (j == 24) { continue Inner; //When j is 24, the continue statement causes that for loop to go to the next iteration. } document.write (j + " "); } } Try/Catch/Finally try/catch/finally lets you deal with exceptions gracefully. It does not catch syntax errors, however (for those, you need to use the onerror event). Try catch recursive try { … } catch (e){ try{ … } //end inner try catch (e){ … } //end inner catch }//end outer catch throw throw "Err2"; The exception can be a string, integer, Boolean or an object On error try/catch/finally does not catch syntax errors. for those, you need to use the onerror event <head> <script type="text/javascript"> window.onerror=function(){ alert('An error has occurred!') } </script> <script document.write('hi </head> type="text/javascript"> there' </script> Debugger tools Vs Fire bug IE debugging tools debugger debugger;//tells the debugger to pause here. debugger You can place debugger statements anywhere in procedures to suspend execution. Using the debugger statement is similar to setting a breakpoint in the code. The debugger statement suspends execution, but it does not close any files or clear any variables. The debugger statement has no effect unless the script is being debugged. The process a function constructs an object Construct objects using constructor new- syntax new constructor ([arguments]) ; //The parentheses can be omitted constructor takes no arguments. new constructor; if //=new constructor() the function as constructor var person=function (name, age){ this.name=name; this.age=age; }; var zs=new person(“zhangsan”,10); var zs2=person(‘z’,10); function Area(){ return 3.14*this.radius*this.radius; } function Circle(radius){ this.radius=radius; } var c=new Circle(); c.Area=Area; Constructor vs call var person=function (name, age){ this.name=name; this.age=age; return {}; }; var zs=new person(“zhangsan”,10); //zs={}; var zs2=person(“z”,10); //{} Constructor vs call var person=function (name, age){ this.name=name; this.age=age; return 1; }; var zs=new person(“zhangsan”,10); //zs={name:”z”,age:10}; var zs2=person(“z”,10); //1 new-actions 1. It creates an object with no members. 2. It calls the constructor for that object, passing a pointer to the newly created object as the this pointer. 3. The constructor then initializes the object according to the arguments passed to the constructor. 4. Return the object if the function returns no object; .prototype Only preceded by function var c=function(){}; var i=new c; i.p1; //undefined. var i2=new c; c.prototype.p1=1; i.p1; //1 i2.p1; //1 c.prototype={}; i.p1; //1 i2=new c; i2.p1; //undefined Every function has an own property: prototype. The object constructed will inherit the prototype Note you cannot change which object to inherit. unless you create a new object after changing function’s prototype. var c=function(){}; var i=new c; i.p1; //undefined. Object.prototype.p1=1; i.p1; //1; c.prototype.p1=2; i.p1; i.p1=3; i.p1; A function’s prototype initially inherits Object.prototype. So constructed object inherits function’s prototype, and then inherits Object.prototype All succeeding Object.prototype Object.prototype predecessor is an object, has no The function’s prototype can change to any other available objects, which all succeed object.prototype. So newly constructed objects will succeed Object.prototype as well. Application of Inheritance function car() { this.wheels=4; } function benz(color) { this.color=color; benz.prototype = car(); audi.prototype benz.prototype; new = } var b = new benz("red"); var a = new audi("blue"); function audi(color) { this.color=color; } alert(b.wheels); //4 alert(a.wheels); //4 Object.prototype inherits none •Default function1.prototype •changable Any object eventually inherits it inherit Object.prototype function1 object1 inherit .prototype Inherit current function1.prototype object2 inheritance not writable .constructor •(Initial function1.prototype).const ructor :=function1 .constructor inherit Object.prototype function1 object1 inherit .prototype object2 •object2 has no .constructor initially •So object2.constructor is got from the inheritance chain Object.protot ype inherit function MyConstructor() {} var myobject = new MyConstructor(); myobject.constructor == MyConstructor; //true function1 object1 inherit .prototy pe object 2 inherit function MyConstructor() {} Object.proto MyConstructor.prototype = {}; type var myobject = new MyConstructor(); //current prototype is {} myobject.constructor == MyConstructor; // false function1 object1 inherit .prototy pe object 2 function MyConstructor() {} MyConstructor.prototype = {}; var myobject = new MyConstructor(); myobject.constructor == Object; //true {}.constructor==Object, a special function instanceof An operator instanceof object1 instanceof constructor1 //constructor1.prototype (current) object1.parents(*) in Eg function MyConstructor() {} MyConstructor.prototype = {}; var myobject = new MyConstructor(); myobject instanceof MyConstructor; // true Eg function MyConstructor() {} var myobject = new MyConstructor(); MyConstructor.prototype = {}; alert([ myobject instanceof MyConstructor, false ! myobject.constructor == MyConstructor, true ! myobject instanceof Object //true ]); // // Built in and host objects Category Native Objects Built In String, Number, Array, Image, Date, Math User-Defined Objects. Host Objects window Object is of the [object] type. Object can be used as a [function] Thus a constructor. Object .prototype function (){[navti ve code]} Object Inherit{1} alert(Object instanceof Object); //true alert(Object instanceof Function); //true alert(typeof Object); //function inherit Object.pr ototype Object Object.prototype Object.prototype.toString switch(this) undefined [object Undefined] null [object Null] Other [object Class] Object.prototype Properties Object.prototype.toString ( ) [object class] Append Property Extensible, not implementable Unless specified otherwise, the [[Extensible]] internal property of a built-in object initially has the value true. Append property Cannot be assigned null an object //exception Primitive: string,number,boolean,undefined they’re immune to appending appendable function object Object.pr ototype inherit Function’s Constructor .prototype Function function (){[navti ve code]} Inherit{1} Function.prototype.a=1; alert(Function.a); Function Object.pr ototype .prototype Function function (){[navti ve code]} Inherit{1} function f() { } alert(f.constructor); alert(f.constructror.constru ctor); alert(Function.constructor); alert(f.constructor.construc tor.constructor); alert(f.constructor.construc tor.constructor.constructo r); inherit (A function)’s Constructor funct ion1 Function the [[Class]] Function is a sub[[Class]] of “Object”[[Class]] Function.prototype Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined. Unless specified otherwise, the [[Class]] internal property of a built-in object is "Function" if that built-in object has a [[Call]] internal property, or "Object" if that built-in object does not have a [[Call]] internal property. Function Instances function function a() { } a=function(){} function (){} new Function() Function(…) String var a = String("a"); var b = new String("b"); alert(typeof a);//string alert(a);//a; alert(typeof b);//object alert(b);//b Date Date() returns a string new Date() returns an object inspect( Date() ); inspect( new Date() ); Math [[Class]] Math Array [[Class]]:Array Date.prototype.toString This function returns a String value. The contents of the String are implementationdependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form. JSON contains two functions, parse and stringify, [[Class]] JSON Extensible [[Construct]] false [[Call]] false RegEx Such as DOM DOM Window document … alert() prompt() confirm() open() Alert(undefined) alert(x) //exception assuming defined yet //alert(typeof(b) =="undefined"?"undefined":blur); aledrt(b); "x" isn't Document.write <html> < body> < h1>My First Web Page</h1> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); < /script> < /body> < /html> Note:Try to avoid using document.write() in real life JavaScript code. The entire HTML page will be overwritten if document.write() is used inside a function, or after the page is loaded. However, document.write() is an easy way to demonstrate JavaScript output in a tutorial. Change the content of Tag <html> < < < <script < < /body> < /html> h1>My First p body> Web Page</h1> id="demo"></p> type="text/javascript"> document.getElementById("demo").innerHTML=Date(); /script> Event Fired by Host Objects event <html> <body onclick="alert(Date()); "> </body> < /html> Types of Execution Code Global Eval function Closure var bind = function (x) { return function (y) { return x + y; }; } var plus5 = bind(5); alert(plus5(3)); this in function function Circle(radius) { this.radius = radius; this.circum =function() { return (radius * 6.28); } } var circle = new Circle(1); alert(circle.circum()); //6.28 circle.radius=10; alert(circle.circum()); //6.28 function Accumulator(start) { function Accumulator(start) { var current = start; return function (x) { return function (x) { start += x; return start; current += x; return current; }; } function Accumulator(start) { return function (x) { }; return start+x; } }; } var a = Accumulator(4); //function(x){return current/start/current;} where current/start is var alert(a); var x = a(5); //x has value 9 alert(x); x = a(2); //x has value 11 ,11, 6 alert(x); var b = Accumulator(42); //current2=42 alert(b); x = b(7); //x has value 49 alert(x); x = a(7); //x has value 18,18, 11 alert(x); function Accumulator(start) { //var current = start; return function (x) { current += x; return current; }; } var a = Accumulator(4); //a=function(x){current+=x;return current;} current is kept from var in Accumulator and current=4 alert(a); var x = a(5); //x has value 9 current=4+5; return 9 alert(x); x = a(2); //x has value 11 //current=9+2 alert(x); var b = Accumulator(42); //current2=42 alert(b); x = b(7); //x has value 49 (current=42 in closure b) //current2=42+7 alert(x); x = a(7); //x has value 18 (current=11 in closure a) //current=11+7 alert(x); where Lambda Lifting //Initial version function sum(n) { if(n == 1) { return 1; } else { function f(x) { return n + x; }; return f( sum(n - 1) ); } } //After converting the free variable n to a formal parameter w function sum(n) { if(n == 1) { return 1; } else { function f(w, x) { return w + x; }; return f( n, sum(n - 1) ); } } //After lifting function f into the global scope function f(w, x) { return w + x; }; function sum(n) { if(n == 1) { return 1; } else { return f( n, sum(n 1) ); } } Further Reading W3schools.com Ecma-international.org Google.com … web Thank You! Window/navigator/document manipulation XmlHttpRequest jquery Script vs Program Suppose you went back to Ada Lovelace and asked her the difference between a script and a program. She‘d probably look at you a script is what you give the actors, but a program is what you give the audience. That Ada funny, then say something like: Well, was one sharp lady…