1 / 35

Javascript Introduction

Javascript Introduction. Kenny Lam. What is Javascript ?. Client-side scripting language that can manipulate elements in the DOM Event-driven language that responds to activity on the webpage In the end, adds an interactive element to the page without having to load a new page. More about….

idola
Télécharger la présentation

Javascript Introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavascriptIntroduction Kenny Lam

  2. What is Javascript? • Client-side scripting language that can manipulate elements in the DOM • Event-driven language that responds to activity on the webpage • In the end, adds an interactive element to the page without having to load a new page

  3. More about… • Dynamic typing • Interpreted language • Object Oriented • Protoypes for inheritance • May be different for different browsers • May be different for different versions of different browsers

  4. JavascriptVariables and Basic Syntax Kenny Lam

  5. Importing your Javascript • Two places to import your javascript • <head> element • End of <body> element OR <head> <script type=“text/javascript” src=“http://location.com/file.js” /> </head> … <body> … <script type=“text/javascript” src=“http://location.com/file.js” /> </body>

  6. Variables • Only one prefix to remember, use var with all your variables when declaring them • Different variable types include (objects later) • Numbers • Booleans • String • Null • Undefined var x = 6.470; var y = ‘hello world’; var s = true;

  7. Variables pt. 2 • Numbers – double precision, be careful of floating point errors • Null – for explicitly saying non-assigned value • Undefined – for never having assigned anything

  8. Strings • Array of characters • Comes with a variety of built-in methods • length, indexOf, match, replace, search, split, substr, substring, toString var s = ‘hello world’; s[1]; // value of ‘e’ s.indexOf(‘\ ’); // value of 5 s.substr(8); // value of ‘rld’

  9. Syntax • Be a clean coder when it comes to javascript, can lead to hazards if not careful • If-else statements. Use blocks • End appropriate lines with semicolons • Use either single or double quotes, but don’t mix and match if (expression) { //code } else { //code } var s = ‘string here’; var x = ‘we can have a “string” inside another!’

  10. Objects • Same as a dictionary/hash table in other languages • Can use strings as keys, helps with disallowed characters • Values are any acceptable var’s • Can even use functions as values (later) var x = 6470; var obj1 = { //the braces create an object key1: x, //use commas to separate keys “key2”: “string” }; //ending my declaration var obj2 = { key: obj1 //can even have an object! };

  11. Objects pt. 2 • Access using object.property • Access using array notation obj1.key1; //will give 6.470 obj1.y = 3; obj2[‘key’]

  12. Special Objects • Two very special objects: window and document • The document object holds the DOM elements • Every window/tab houses everything inside of the window object document.body; //returns the <body> element window.location; //gives the URL for the window

  13. Arrays • Special type of objects, using numbers as keys • Has many special methods • length, push, pop, concat, toString vartmpArray = [“string”, 6.470, obj1]; //different variable types are okay tmpArray[0]; //value “string” tmpArray[2].key1; //value 6.470

  14. The console • Console logging • Shows visibility of object properties • Web page source code • Breakpoints console.log(obj1);//you can see all its properties console.log(“message”); console.log(array1); //can read all elements

  15. JavascriptOperators and Functions Kenny Lam

  16. Operators • All the common mathematical operators • +, -, *, /, % (mod) • Unary operators • Compound assignment • Overloaded + operator for strings • More operators in Math module for numbers (use Math.pow, not the carat) x++; ++x; x*=3; “string1” + “string2”; // gives “string1string2” “3” + 8 // gives “38” “1” + 2 + 3 // gives “123”

  17. Operators pt. 2 • Comparison operators: • <, <=, >, >= • For non-strict equality comparisons, can use == • For strict equality comparisons, use === • Also non-equality comparisons: • !=, !==

  18. Functions • Functions are objects, two ways of declaring • Just use number of parameters because of dynamic typing function fun(x,y) { //will take 2 parameters //code }; varfunFunc = function(a,b,c) { //uses 3 parameters //code }; fun(“string”, obj1); fun(obj1, obj2); //these two call the same function!

  19. Functions pt. 2 • Lots of bad flexibility. Function calls don’t need to match signature! • If you need a variable number of arguments, use the arguments object fun(x,y); fun(x,y,z); //these will both call the same function function abc() { arguments.length; arguments[0]; //more code }

  20. Functions pt. 3 • Object properties can be functions too(since functions are objects) • Functions return undefined by default, but can return any value • Recursive calls

  21. Scope • Functions define scope of variables • The ‘this’ reference • Anonymous functions, closure, and inner functions are fun ways to play with this var x = 13; function scopeFun() { var x = 12; console.log(x); //value of 12 console.log(this.x); //value of 13 }; //helps to show why to use var!

  22. Execution • Javascript is executed in the order written • To get asynchronous behavior, use setTimeoutor AJAX calls (more later)

  23. JavascriptClasses and Inheritance Kenny Lam

  24. Object Oriented • Can create classes in javascript, defined by functions (constructors) • The ‘new’ keyword makes a new object and sets up the constructor correctly function MITClass(course, semester){ this.course = course; this.semester = semester;} var web = MITClass(6.470, “IAP 2013”); web.course; //value 6.470 web.semester; //value “IAP 2013”

  25. Prototypes • In javascript, you inherit from instances instead of classes • The ‘__proto__’ property of objects, and the ‘prototype’ property of functions var x = MITClass(6.470, “IAP 2013”); x.prototype; //undefined, x is an object! MITClass.__proto__; //bogus, MITClass is a function! x.__proto__; //some object MITClass.prototype; //same object x.__proto__ == MITClass.prototype; //true x.__proto__ === MITClass.prototype; //true

  26. JavascriptConditionals and Loops Kenny Lam

  27. Conditionals • If-else statements • Switch statements if (condition) { if(condition) { //code //code } else { else if(condition) { //code //code } } else { //code } switch(variable) { case 1: //code break; case 2: //code break; default: //code }

  28. Looping • For loops • While loops • Do…while loops vari=0; for(vari=0; i<n; i++) { while(i<n) { //code //code } } for(var x in ObjectName) { ObjectName[x]; //code }

  29. JavascriptjQuery Kenny Lam

  30. About jQuery • Open source aid to writing effective javascript • Bundles all the power of javascript into more manageable API • Cross-browser support • Handles events, manipulates DOM, provides animations • Wait for DOM to load properly $(document).ready() $; //the dollar is shorthand for jQuery jQuery; //also jQuery (surprise) var x = jQuery.noConflict();

  31. Selectors • Any CSS style selectors are valid • Most typical will be id, class, and element type selectors $(‘#id’) //select elements using the hash prefix $(‘.class’) //select elements using the dot prefix $(‘div’) //select elements by node type $(‘div:first’).parent() //select parent of first div

  32. Events • Provides a great way to handle events • Read the documentation for all possible events • Common events • click, blur, keypress, focus, hover, submit, etc. $(‘#id’).click(function(event) { //code to execute on a click of #id element });

  33. Extras • jQuery can also do loops that integrate well with selectors • The jQuery API is used for jQuery objects. Be careful of ‘this’ $(‘div’).each(function() { //code }); $(‘div’).click(function() { //you can reference ‘this’ in here and it will mean the clicked div //but you might really want $(this) });

  34. JavascriptMore Reading Kenny Lam

  35. Additional Topics • Console/debugging • Cookies • Closures • Regex • Storage • Anonymous/named anonymous functions • Other cool javascript libraries! (Raphael, lightbox, scriptaculous, jQuery UI, prototype, mooTools, etc.)

More Related