Lecture 6: Advanced Javascript Flashcards
What are functions?
Functions are reusable blocks of code
− are defined by the key word function
− have a unique function name
− can have parameters and/or return values
− need to be called to execute the code
Function syntax
function greet(person) {
let greeting = “Hello “ + person + “!”;
return greeting;
}
// calls the function once, store the return value
let greetingText = greet(“Venkat”);
Scope
What the function sees and has access to
Global Scope
accessible everywhere
Example: const x = 1 is declared outside of the function
Calling variables that the global scope cannot see
Reference Error
Events
functions that are called by Javascript on interactions
You define the function that should be executed
Event Handler / Callback function
And declare, when it should be called
Event Listener
Event Example
const container = document.querySelector(‘#container’);
container.addEventListener(‘click’, onClick);
Event Parameters
You must know what event types are available in Javascript
Example: Click
Resource: mdn web docs
(‘click’, onClick); = (event type, event handler)
Mouse Event Properties
Target: which HTML element threw the event
Button: which buttons were pressed
clientX / clientY: relative to current view/browser (generally useful)
screenX / screenY: relative to screen
pageX / pageY: relative to page, incl. Scrolled contents
Types of Events
The user selects, clicks, or hovers the cursor over a certain element <= common
The user chooses a key on the keyboard <= common
The user resizes or closes the browser window
Object
collection of related data and/or functionality
Object Literal
const objectName = {
member1Name: member1Value,
member2Name: member2Value,
member3Name: member3Value
};
Multiple objects
create a function that
creates and returns a new objec
Calling a constructor
− create a new object
− bind this to the new object, so you can refer to it
− run the code in the constructor
− return the new object.
Constructors, by convention, start with a capital letter and are named for the
type of object they create
Constructor example
const salva = new Person(‘Salva’);
salva.name;
salva.introduceSelf();
//Hi! I’m Salva.
This
this refers to the current object the code is being written inside
▪ in this case: this this is equivalent to Person
− enables you to use the same method definition for every object you create