Week 7.pdf
Document Details
Uploaded by ZippyPelican
null
Tags
Full Transcript
CP476 Internet Computing Week 7 – 1 JavaScript – fundamentals Shaun Gao, Ph.D., P.Eng. Objectives Introduction to nodeJS JavaScript Data types Operators Functions Variables and constants Strings Numbers Introduction to nodejs Apache – web server Nodejs – another web server 24 minutes video https://w...
CP476 Internet Computing Week 7 – 1 JavaScript – fundamentals Shaun Gao, Ph.D., P.Eng. Objectives Introduction to nodeJS JavaScript Data types Operators Functions Variables and constants Strings Numbers Introduction to nodejs Apache – web server Nodejs – another web server 24 minutes video https://www.youtube.com/watch?v=U8XF6AFGqlc Introduction to nodejs – cont. Nodejs Node.js is an open-source, cross-platform, backend JavaScript runtime environment that runs on Google's V8 JavaScript engine and executes JavaScript code outside a web browser. Node.js lets developers use JavaScript for serverside scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Node.js has an event-driven architecture capable of asynchronous I/O. Node.js was written initially by Ryan Dahl in 2009. JavaScript – data types JavaScript data types Boolean type Undefined type Number type String type Symbol type Object In JavaScript, an object is a standalone entity, with properties and type. let x = {firstName:“Mark", lastName:“Wang"}; JavaScript data type is determined dynamically, based on the value stored Demo00 JavaScript – operators JavaScript Operators are similar to PHP operators. Assignment Operators Comparison Operators Bitwise operators JavaScript – assignment operator Assignment operator JavaScript – Comparison operators Comparison Operators JavaScript – bitwise operators JS bitwise Operators Question? >> vs. >>> JavaScript – functions JavaScript Function Syntax A JavaScript function is defined with the function keyword, name and parentheses (). function function_name(parameter1, parameter2, parameter3) { // code to be executed } Difference between function_name and function_name() in JavaScript function_name refers to the function object while function_name() refers to the function execution result. JavaScript – functions – cont. Display function object function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } console.log( toCelsius ); // it will be compile error for C++ Display function execution result function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } console.log( toCelsius(77) ); Demo01 JavaScript – Variables and constants JavaScript has 3 types of scopes. Block scope Variables declared inside a { } block with either let or const cannot be accessed from outside the block. Function scope / Local Scope Variables declared within a JavaScript function, become LOCAL to the function. Global scope A variable declared outside a function, becomes GLOBAL. JavaScript Global Variable: A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function. Question: variable scope difference between PHP and JS? JavaScript – Variables and constants There are 3 ways to declare a JavaScript variable: Using var: var keyword is used to declare variables since JavaScript was created. Using let: Variables defined with let cannot be redeclared. It is the new and recommended way of declaring variables in JavaScript. Using const: inherit from C/C++; it cannot be changed once assigned a value. All JavaScript variables must be identified with unique names. These unique names are called identifiers. Syntax: Declaration: var variable_name; let Var_name; const v_name = fixed value; JavaScript – Variables and constants – cont. Identifier let Variables defined with let cannot be Redeclared. With var it is fine. let x= “Lunshan”; let x= “Shaun”; // SyntaxError: 'x' has already been declared. Variables defined with let must be Declared before use. With var it is fine carName = "Saab"; let carName = "Volvo"; Variables defined with let have Block Scope. Demo02-0 Difference between var and let var declaration is function scoped and let is block scoped. Example: Demo02 JavaScript – Variables and constants JavaScript hoisting Variables defined with var are hoisted to the top and can be initialized at any time. (means: You can use the variable before it is declared with var) With let, you cannot use a variable before it is declared. Block Scope JavaScript provides Global Scope, Function Scope, and Block Scope. A block scope is denoted with { } Variables declared inside a { } block with let cannot be accessed from outside the block. A const variable cannot be reassigned Constant Objects, You can change the properties of a constant object. JavaScript – Strings JavaScript Strings A string is zero or more characters written inside quotes (single or double). let text = "John Doe"; String Length use the built-in length property let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; text.length; Escape Character The problem: let text = "We are the so-called "Vikings" from the north."; The solution to avoid this problem, is to use the backslash escape character. let text = "We are the so-called \"Vikings\" from the north."; JavaScript – Strings – cont. JavaScript strings methods Extracting String Parts, a string has the following methods. slice(start, end) substring(start, end) substr(start, length) Replacing String Content, a string has replace() method replaces a specified value with another value. let text = "Please visit Kitchener!"; let newText = text.replace("Kitchener", "Waterloo"); Demo03 JavaScript - Numbers JavaScript has only one type of number. Numbers can be written with or without decimals. It is always 64-bit floating Point. JavaScript uses the + operator for both addition and concatenation. Numeric Strings JavaScript will try to convert strings to numbers in some numeric operations JavaScript – Numbers – cont. NaN is a JavaScript reserved word indicating that a number is not a legal number. let x = 100 / "Apple"; // x will be NaN (Not a Number) Infinity let x = 2 / 0; let y = -2 / 0; // x will be Infinity // y will be -Infinity Number Methods A number’s toString() method returns a number as a string. Demo04 Summary Introduction to nodejs JavaScript Introduction Syntax Data types Operators Functions Variables and constants Strings Numbers Announcement Group project Please start your group project if you have not yet. The data files have been uploaded in myls. Tutorial: install node.js and setup VS code for running JS CP476 Internet Computing Week 7 – 2 JavaScript – Objects Shaun Gao, Ph.D., P.Eng. Objectives Introduction to JavaScript JavaScript Objects Definition Properties Methods Accessors Constructors Prototypes Object Map() Tutorial: install node.js and setup VS code for JS Introduction What is JavaScript? Language developed by Netscape Primary purpose is for "client-end" processing of HTML documents Originally, JavaScript code is embedded within the html of a document An interpreter in the browser interprets the JavaScript code when appropriate Note that, unlike PHP scripts, JavaScripts are visible in the client browser Since they are typically acting only on the client, this is not a problem Becoming both client-side and server-side programming language JavaScript is an object-based language. JavaScript Objects A JavaScript object is a standalone entity with properties and type Almost "everything" is an object in JavaScript except primitive data type (number, string, Boolean, undefined). Note: objects are created with classes in C++, C#,… JavaScript variables could be Objects Object values are written as name : value pairs (or key:value pairs) let person = {firstName:"John", lastName:"Doe", age:25, eyeColor:"blue"}; A JavaScript object is a collection of named values Object Properties: the named values are called properties JavaScript Objects – cont. In JavaScript, an object can be created in three ways: 1) using Object Literal/Initializer Syntax 2) using new operator 3) using the Object() Constructor function with the new keyword or create(). Examples: 1) var p1 = { name:“John" }; // object literal syntax 2) var p2 = new Car(‘BMW’, ‘red’); //Car can be either a function or a class such that an object 3) var p2 = Object.create(car); // Object() constructor function p2.name = “John"; // property Demo01 JavaScript Objects – cont. Create JavaScript Object using Object Literal Syntax Syntax: var object-name = { key1: value1, key2: value2,...}; Note: the values can be string, number(integer, float), Boolean etc. Create JavaScript Objects using Objects() Constructor Syntax: var ObjectName = new Object(); //this is a variant of new operator Three difference ways to create an object. Demo02 JavaScript Objects – cont. The following is not JavaScript objects. Primitive values or primitive data types are not objects in JavaScript. Undefined strings numbers Boolean Symbols which returns from Symbol() Symbol() is a built-in function, returns a symbol primitive A Symbol value represents a unique identifier. Every Symbol() call is guaranteed to return a unique Symbol. Primitive data type is a basic data type provided by a programming language as a basic building block. Demo03 JavaScript - Creating an Object Note on creating JavaScript objects An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. Example: const myObj = new object(); myObj.type = 'Dot syntax'; myObj['date created'] = 'String with space’; myObj.date created = 'String with space’; Demo04 JavaScript - Object Properties A JavaScript object property is a characteristic of an object, often describing attributes associated with a data structure. There are two kinds of properties: instance properties hold data that are specific to a given object instance. static properties hold data that are shared among all object instances. static key word defines a static method or a static property. Question? How does static key word work in PHP? A property has a name (a string, or symbol) and a value (primitive, method, or object reference). JavaScript - Object Properties How to access JavaScript Properties Syntax person.firstname + " is " + person.age + " years old."; Demo05 JavaScript - Object Methods JavaScript Methods – it can be located at value location in key : value JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition. const person = { firstName: “Mike”, lastName: “Jiang", age: 24, fullName: function() { return this.firstName + " " + this.lastName; } }; How to access Object Methods Syntax: objectName.methodName(); example: let name = person.fullName(); Demo06 JavaScript - Object Accessors JavaScript Accessors (Getters and Setters) The get Keyword Syntax get function_name(){ … return something; } Example const person = { firstName: “Melia", lastName: “Hay", language: "en", get lang() { return this.language; } }; person.lang; not person.lang(); The set Keyword Syntax set function_name(){ … set something; } JavaScript - Object Accessors The set Keyword Example const person = { firstName: “Lily", lastName: “Hua", language: "", set lang(lang) { this.language = lang; } }; // Set an object property using a setter: person.lang = “jp"; not like person.long(“jp”); Demo07 – getter and setter JavaScript - Object Constructors Sometimes we need a "blueprint" for creating many objects of the same "type". Object constructor function create an "object type" function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } Objects of the same type are created by calling the constructor function with the new keyword: const myFriend = new Person(“Max", “Doe", 24, “gray"); JavaScript - Object Constructors – cont. You can add properties or methods to an object You can add properties or methods to a constructor function function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; this.name = function() { return this.firstName + " " + this.lastName; }; } JavaScript - Object Prototypes We cannot add a new property to an existing object constructor from outside of the object constructor. function Person(first, last, age, eyeColor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyeColor; } Person.nationality = "English"; Demo08 JavaScript - Map Objects A Map object holds key-value pairs where the keys can be any datatype. Essential Map() Methods: Demo09 (nested object) Summary JavaScript objects Definition Properties Methods Accessors Constructors Prototypes Object Map() Question? Key word this is used in both PHP and JS, any difference? Announcement Please start your group project The data files for the project are in myls Tutorial: install node.js and setup VS code for JS