Understanding JavaScript Object-Oriented Programming

tutorial 4 n.w
1 / 30
Embed
Share

Explore the fundamentals of JavaScript as an object-oriented language, covering objects, properties, methods, keywords, strings, numbers, statements, and Math object tasks. Dive into JavaScript's OOP concepts with practical examples and essential JavaScript keywords.

  • JavaScript
  • OOP
  • Objects
  • Methods
  • Programming

Uploaded on | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Tutorial 4 JavaScript as OOP Yu Jianwei Email: jwyu@se.cuhk.edu.hk Department of Systems Engineering and Engineering Management 1

  2. JavaScript and Objects Technically, Everything in JavaScript is Object Array, String, Number, An object contains properties and methods Property has a name and value Methods are actions that can be performed on the object 2

  3. Some Important JavaScript Keywords Keyword String Number Operators Statements Math Date Array Boolean Error Global Conversion Description To manipulate text strings To manipulate numbers To assign values, compare values, perform arithmetic operations Instructions" to be "executed" by the web browser in HTML To manipulate calculations Retrieves and manipulates dates and times Creates new array objects Creates new Boolean objects Returns run-time error information Represents global variables and contains various built-in JS methods Converts different JS values to Number, String, Boolean 3

  4. String Case sensitive String Methods: s.length; s.indexOf( to ) ; s.slice(3,7); s.replace( CUHK , HongKong ); s.toLowerCase(); s.concat(" ", "Campus"); s.charAt(1); var s = Welcome to CUHK 4

  5. Number Numbers can be written with scientific notation e.g. var y = 123e-5; Number Methods Number.isFinite(x) ; Number.isInteger(x); Number.isNaN(x); x.toPrecision(3); x.toString(); . var x = 2.017; 5

  6. Statements JavaScript statements often start with a statement identifier while (i < 10){ } if (i < 10){ } else if{ } else{ } for (i =0; i < 10; i++ ){ } 6

  7. Statements try { //code to try to run } catch(error){ // code to handle errors } finally{ // code executed regardless of the try / catch result } switch (i){ case 1: break; case 2: break; default: } 7

  8. Math Math object allows you to perform mathematical tasks. Math methods: Math.PI; Math.pow(2,3); Math.sqrt(64); Math.abs(-3.17); Math.ceil(3.17); Math.floor(3.17); Math.random(); Math.max(0,10,6,55); 8

  9. Date Date object works with dates and times Four ways to instantiate a date: var d = new Date(); var d = new Date(milliseconds); //zero time is 01 Jan 1970 00:00:00 UTC var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); 9

  10. Date Methods d.getDate(); //get day as a number(1-31) d.getFullYear(); //get the four digit year(yyyy) d.setDate(15); //set day as a number(1-31) d.setFullYear(2100,0,14); //sets a date object to a specific date Date.parse("March 21, 2012"); // returns the number of milliseconds between the date and January 1, 1970 10

  11. Array Array object is used to store multiple values in a single variable. e.g. var fruits = [ banana , apple , orange ]; Array indexes are zero-based. e.g. fruits[0] = banana ; Array elements can be objects, like functions or arrays. e.g. myArray[0] = Date.getDay(); myArray[1] = fruits; 11

  12. Array Methods Popping and Pushing x=fruits.pop(); // removes the last element, return the last element y=fruits.push( Mango ); // adds element Mango to array fruits, return the length of new array Shifting Elements x=fruits.shift(); // removes the first element, return the first element. y=fruits.unshift( Lemon ); // add element Lemon to array fruits, return the length of new array Deleting Elements delete fruits[1]; // change the second element in fruits to undefined Using delete may leave undefined holes in the array. Use pop() or shift() instead. var fruits = [ Banana , Apple , Orange ]; 12

  13. Array Methods var fruits = [ Banana , Apple , Orange ]; var color = [ red , blue ]; var points = [21,14,17,61,8]; Splicing an Array fruits.splice(1,2, Lemon ); The first parameter defines the position where to add new elements The second parameter defines how many elements should be removed The rest parameters define the new elements to be added Merging Arrays new_arr=fruits.concat(color); // concatenates array fruits and color fruits don t change here!!! Sorting an Array By default, sort() function sorts value as strings fruits.sort(); // sort an array alphabetically fruits.reverse(); // sort an array in descending order points.sort(function(a,b){ return a-b}); //numeric sort points.sort(function(a,b){ return b-a}); //numeric sort in descending order 13

  14. Conversion The table below shows the result of converting JS values to Number, String, and Boolean Original Value Converted to Number Converted to String Converted to Boolean false 0 "false" false true 1 "true" true "0" 0 "0" true "1" 1 "1" true "20" 20 "20" true "twenty" NaN "twenty" true [ ] 0 "" true [20] 20 "20" true [10,20] NaN "10,20" true ["ten","twenty"] NaN "ten,twenty" true 14

  15. JavaScript Common Mistakes Mistake Types Accidentally Using the Assignment Operator Expecting Loose Comparison Confusing Addition & Concatenation Misunderstanding Floats Breaking a JavaScript String Misplacing Semicolon Breaking a Return Statement Accessing Arrays with Named Indexes Ending Definitions with a Comma Undefined is Not Null Expecting Block Level Scope 15

  16. Accidentally Using the Assignment Operator Description Examples: JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment operator (=), instead of a comparison operator (==) in an if statement. var x = 0; if (x = 10) // returns true, bec 10 is true if (x == 10) // returns false, bec x is not equal to 10 if (x = 0) // returns false, bec 0 is false 16

  17. Expecting Loose Comparison Description Examples: In regular comparison, data type does not matter. var x = 10; var y = 10 ; In strict comparison, data type does matter. if (x == y) // returns true if (x === y) // returns false It is a common mistake to forget that switch statements use strict comparison. switch(x) { case 10 : alert( Hello ); // not display case 10: alert( Hello ); // display } 17

  18. Confusing Addition & Concatenation Description Examples: Addition is about adding numbers. var x = 10 + 5; // x = 15 Concatenation is about adding strings. var y = 10 + 5 ; // y = 105 In JavaScript both operations use the same + operator. Because of this, adding a number as a number will produce a different result from adding a number as a string 18

  19. Misunderstanding Floats Description Examples: All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). var x = 0.1; var y = 0.2; var z = x+y; // z will not be exactly 0.3 All programming languages, including JavaScript, have difficulties with precise floating point values To solve the problem, using var z = (x*10+y*10)/10; // z will be 0.3 19

  20. Breaking a JavaScript String Examples: var x = Hello World ; //correct Description JavaScript will allow you to break a statement into two lines But, breaking a statement in the middle of a string will not work var x = Hello World ; //wrong You must use a "backslash" if you must break a statement in a string var x = Hello \ World ; //correct 20

  21. Misplacing Semicolon Description Examples: Because of a misplaced semicolon, this code block will execute regardless of the value of x if (x == 19); { //code block } 21

  22. Breaking a Return Statement Description It is a default JavaScript behavior to close a statement automatically at the end of a line Examples: function myFunction(a) { var power = 10; return a * power; } Same reults function myFunction(a) { var power = 10 return a * power } Same reults function myFunction(a) { var power = 10; return a * power; } function myFunction(a) { var power = 10; return; a * power; } function myFunction(a) { var power = 10; return a * power; } 22

  23. Explanation If a statement is incomplete like: var JavaScript will try to complete the statement by reading the next line: power = 10; But since this statement is complete: return JavaScript will automatically close it like this: return; This happens because closing (ending) statements with semicolon is optional in JavaScript. JavaScript will close the return statement at the end of the line, because it is a complete statement. 23

  24. Accessing Arrays with Named Indexes Examples: var person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; var x = person.length;// person.length will return 3 var y = person[0];// person[0] will return "John" Description Many programming languages support arrays with named indexes Arrays with named indexes are called associative arrays (or hashes) JavaScript does not support arrays with named indexes In JavaScript, arrays use numbered indexes 24

  25. Accessing Arrays with Named Indexes Description Examples: In JavaScript, objects use named indexes var person = []; person["firstName"] = "John If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object person["lastName"] = "Doe"; person["age"] = 46; var x = person.length;// person.length will return 0 After the automatic redefinition, array methods and properties will produce undefined or incorrect results var y = person[0];// person[0] will return undefined 25

  26. Ending Definitions with a Comma Description Examples: Trailing commas in object and array definition are legal in ECMAScript 5 person = {firstName:"John", lastName:"Doe", age:46,} // ECMAScript 5 Internet Explorer 8 will crash. JSON does not allow trailing commas. person = \ {"firstName":"John", "lastName":"Doe ", "age":46} // JSON 26

  27. Undefined is Not Null Description Examples (Assume myObj is undefined): JavaScript objects, variables, properties, and methods can be undefined if (typeof myObj === "undefined") //correct if (myObj === null) //incorrect if (myObj !== null && typeof myObj !== "und efined") //incorrect empty JavaScript objects can have the value null if (typeof myObj !== "undefined" && myObj !== null) //correct You can test if an object exists by testing if the type is undefined 27

  28. Expecting Block Level Scope Description Examples: JavaScript does not create a new scope for each code block for (var i = 0; i < 10; i++) { // some code } return i; //This code will display the value of i (10), even OUTSIDE the for loop block 28

  29. Resources https://www.w3schools.com/js/default.asp https://www.w3schools.com/jsref/default.asp https://www.w3schools.com/Js/js_mistakes.asp 29

  30. Questions and Answers 30

Related


More Related Content