🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

CP476 Internet Computing Week 8 – 1 JavaScript – functions Shaun Gao, Ph.D., P.Eng. Objectives Introduction JavaScript functions Function declaration Function expression Function hoisting Arrow function Parameters call() apply() bind() Introduction How JavaScript code is executed? (all scripting lan...

CP476 Internet Computing Week 8 – 1 JavaScript – functions Shaun Gao, Ph.D., P.Eng. Objectives Introduction JavaScript functions Function declaration Function expression Function hoisting Arrow function Parameters call() apply() bind() Introduction How JavaScript code is executed? (all scripting language same) Functions First, definition/declaration Secondary, execution The meaning of hoisting JavaScript - Function declaration JavaScript functions are defined with the function keyword in general There are two methods to define a JavaScript functions. Function Declaration and Function Expression Syntax of the function declaration function functionName([param1[, param2[,..., paramN]]]) { statements “the body of the function”; } Syntax of the function expression function [name]([param1[, param2[,..., paramN]]]) { statements “the body of the function”; } Inside of [ ] are options. JavaScript - Function declaration – cont. Function Declaration vs. Function Expression Declaration: Function declarations load before any code is executed. Expression: Function expressions load only when the interpreter reaches that line of code. Question? Declarations: the function declaration is hoisted to the top of other code. Expression: Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined. Function expression can define anonymous functions whereas function declaration cannot. Demo01 JavaScript - Function Hoisting Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope automatically before code execution. Function hoisting – JavaScript code re-ordering JavaScript functions can be called before they are declared when function declaration is used. var ret=myFunction(5); console.log(ret); function myFunction(y) { return y * y; } Demo02 JavaScript – Arrow Function An arrow function expression is a type of function expressions. Basic syntax (1) param => expression (2) (param1, paramN) => expression (3) param => { let a = 1; return a + param; } (4) (param1, paramN) => { let a = 1; return a + param1 + paramN; } Demo03 JavaScript – Arrow Function –cont. Arrow function Limitations Does not have its own bindings to this or super and should not be used as methods. Does not have new.target keyword. You can detect whether a function or constructor was called using the new operator. Not suitable for call, apply and bind methods, which generally rely on establishing a scope. Can not be used as constructors. JavaScript Function Parameters Function Parameters and Arguments function functionName(parameter1, parameter2, parameter3) { // code to be executed } Function parameters are the names listed in the function definition. Function arguments are the real values passed to the function. In JavaScript: function definitions do not specify data types for parameters. functions do not perform type checking on the passed arguments. functions do not check the number of arguments received. JavaScript Function Parameters – cont. JavaScript functions have a built-in object called the arguments object. The argument object contains an array of the arguments used when the function was called. JavaScript functions have both properties and methods. arguments.length property, it returns the number of arguments when the function is called. function myFunction(a, b) { return arguments.length; } toString() method returns the function as a string function myFunction(a, b) { return a * b; } let text = myFunction.toString(); Demo04 JavaScript Function Parameters – cont. Default Parameters – similar to PHP If a function is called with missing arguments (less than declared), the missing values are set to undefined, JavaScript keeps running. A parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will use the default values of undefined. Syntax function function_name(parameter1, parameter2=value2…){……} function myFunction(x, y=2) {……} JavaScript - Function Invocation Invoking a Function as a Function function myFunction(a, b) { return a * b; } myFunction(10, 2);  inherited from C, Invoking a Function as a method of an object const employee ={ firstName: “Mike”, lastName: “He”, fullName: function() { return this; } } employee.fullName.call(); Invoking a Function with a Function Constructor (the F is capital) new Function(functionBody) new Function(arg1,... argN, functionBody) Demo05 JavaScript - Function call() In JavaScript all functions are object methods. The call() method is a predefined method of function objects. const person = { fullName: function() { return this.firstName + " " + this.lastName; } } const person1 = { firstName:"John", lastName: "Doe" } person.fullName.call(person1); // This will return "John Doe": JavaScript - Function call() – cont. The call() method with Arguments const person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } const person1 = { firstName:"John", lastName: "Doe" } person.fullName.call(person1, "Oslo", "Norway"); Demo06 JavaScript Function apply() The apply() method is similar to the call() method, it is also a predefined method of function objects const person = { fullName: function() { return this.firstName + " " + this.lastName; } } const person1 = { firstName: "Mary", lastName: "Doe" } person.fullName.apply(person1); // This will return "Mary Doe": JavaScript Function apply() – cont. The apply() method with Arguments const personY = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } const personY1 = { firstName:“Mary", lastName: "Doe" } personY.fullName.apply(personY1, ["Oslo", "Norway"]); Demo07 JavaScript Function bind(). bind() creates a new function by using function object, that will force the this inside the function to be the parameter passed to bind(). Syntax: func.bind(thisArg) In this syntax, the bind() method returns a copy of the function func with the specific this value (thisArg). Demo08 bind() only apply to function objects not for function calls Demo09 Comparison among call(),apply(), bind(). The Difference Between call() and apply() The call() method takes arguments separately using comma. The apply() method takes arguments as an array. A useful mnemonic is "A for array and C for comma." Summary JavaScript functions Function declaration Function expression Function hoisting Arrow function Parameters call() apply() bind() Announcement Group project progress Project report due date: Mar. 25 Test 2 (cover week 5-8) next week (Mar 15) at 1:30 pm Bring your laptop CP476A Internet Computing Week 8 – 2 JavaScript – JS classes and Async Shaun Gao, Ph.D., P.Eng. Objectives JavaScript class Introduction Inheritance JavaScript (Node.js) event driven Event queue Event loop JavaScript Asynchronous JS Synchronous vs. Asynchronous JS callback callback hell async and await keywords JavaScript – Class introduction A JavaScript Class is a program-code-template for creating objects. Syntax class ClassName { constructor() {... } method_1() {... } method_2() {... }... } //"constructor“ is a special method // constructor does not have a name Example Demo01 Getter/setter can be inside of class JavaScript – Class Inheritance class inheritance uses the extends keyword. A child class inherits all the methods from its parent class. the super() method in the constructor method means the parent's constructor is called. Demo02 JavaScript – Class Inheritance Public and private By default, all methods and variables in a class are public. but private members in a class can be created by using a hash # prefix. Private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. The # is a part of the name itself. Demo03 JavaScript (The get and set Keyword) Syntax {get prop() {...; return property; }} Syntax: {set prop(val) {... }} Example. Demo04 Note: (1) even if the getter is a method, do not use parentheses when calling them; (2) get and set keywords can be used outside of classes Node.js (JavaScript) event driven Event: In software design, an event is an action or occurrence recognized by software. Examples: mouse move events, mouse clicks, network IO, operating system interrupts, etc. Event Queue: An event queue is a repository where events from software are held prior to being processed by a receiving program or system. Node.js Event loop Node.js event loop Node.js event loop is mechanism that allows Node.js to perform nonblocking I/O operations — despite the fact that JavaScript is singleprocess — by offloading operations to the system kernel whenever possible. JavaScript - Asynchronous Synchronous in JavaScript? Synchronous means to be in a sequence such that every statement of the code is executed one by one. So, basically a statement has to wait for the earlier statement to complete. What is the problem? Asynchronous in JavaScript Asynchronous means to allow the program to be executed immediately without waiting for the earlier statement to complete. Adding Events to the Queue One way for JavaScript programs to add events to the event queue is via a call to setTimeout() – force a program to wait for setTimeout() is a function that accepts two parameters an event handler (i.e. a function), and a delay in milliseconds: the delay before the handler gets added to the event queue This causes a timer to be created it executes immediately and waits for the specified delay it then adds a timeout event to the queue with the specified event handler The JavaScript engine will then process that event as normal when timeout Demo05 JavaScript - Callback function A function that is passed as an argument to another function is called a callback function. That means, callback functions are just any JavaScript function, but can be used as argument for another function. The traditional way of handling asynchronous events in JavaScript is by using a callback. Why we need callback functions? JavaScript is an event-driven language which means the flow of the program is determined by events. When JavaScript code has some events involved, instead of normally line-by-line, top-to-bottom execution, and waiting for a line to execute, it just skips the line cannot be executed right away, executes the next lines and moves back in an appropriate time. JavaScript - Callback function – cont. Example: function addition(a, b, callback) { let result = callback(a, b); console.log("The result is: " + result); } function addTo(a, b) { return a + b; } addition(5, 8, addTo); When you pass a function as an argument, remember not to use parenthesis. Demo06 JavaScript - Callback function – cont. Callback functions in asynchronous code Using setTimeout() function Example: function first() { setTimeout(function() { console.log('first’); }, 10);  anonymous function } function second() { console.log('second'); } first(); second(); Demo07 JavaScript - Callback Hell Callback hell is a phenomenon that callbacks are nested when a developer tries to execute multiple asynchronous operations one after the other. It is error-prone, hard to read, and hard to maintain code. Techniques to fix callback hell Using async-await keywords Using promises JavaScript – async function and await An async function is a function declared with the async keyword, and the await keyword is permitted within the function. The async and await keywords enable asynchronous. The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code Syntax async function_name([param[, param[,...param]]]) { statements = await otherFunctName(); …… } JavaScript – async function and await Demo08-async Summary JavaScript class Introduction Inheritance JavaScript event driven Event queue Event loop JavaScript Asynchronous JS Synchronous vs. Asynchronous JS callback callback hell async and await keywords Question? Announcement JavaScript Practices Group project progress Project report due date: Mar. 25 Test 2 (cover week 5-8) next week (Mar 15) at 1:30 pm Bring your laptop

Tags

javascript functions programming
Use Quizgecko on...
Browser
Browser