Week 01 → Day 003 → Wed → August 9, 2017
Index
Coding Challenge #1 longestString
Review
Basic JavaScript Review
Lecture ⋰ this
⋰ new
⋰ call()
⋰ apply()
⋰ Closures ⋰class
⋰extends
⋰getter
⋰ Callbacks
Advanced JavaScript Review ⋰
Lecture https://youtu.be/tkauGGGxK_0
Four Rules of this
// 1. Whenever a function is contained in the GLOBAL scope, the value of 'this' inside of that function will be the WINDOW object.
// 2. Whenever a function is called by a PRECEEDING DOT, the object before the dot is "this"
// 3. Whenever a CONSTRUCTOR FUNCTION is used, 'this' refers to the 'SPECIFIC INSTANCE OF THE OBJECT'
// that is created and returned by the constructor function.
// 4. Whenever call or apply method is used, 'this' is explicitly defined.
this
doesn't work with anonymous functions 5:08
In the function declaration below, this
isn't defined, so it points to the global (Window) object.
function greet(name) {
console.log(`Hello ${name}`); // "Hello frank"
console.log(this); // this points to the Window object
}
greet('frank')
2. Whenever a function is called by a PRECEEDING DOT, the object before the dot is this
12:00
greeting: 'Hello my name is',
name: 'frank',
introduce: function() {
console.log(`${this.greeting} ${this.name}`); // this looks outside the introduce scope to the properties this is bound to
console.log(this); // this points to object me
}
};
me.introduce()
3. Whenever a CONSTRUCTOR FUNCTION is used, this
refers to the 'SPECIFIC INSTANCE OF THE OBJECT' that is created and returned by the constructor function 17:30
// Constructor Function
function Person(options) {
this.firstName = options.firstName; // this refers to the instance of the object Person
this.lastName = options.lastName; // this refers to the instance of the object Person
this.greet = function() {
console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
};
};
Person({firstName: 'Ryan', lastName: 'Hamblin'});
new
operator 21:58
The new
operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function. In the example below, we're using new
to create a new Person object.
const frank = new Person({firstName: 'Frank', lastName: 'Faustino'});
console.log(frank); // frank is an object
frank.greet(); // "Hello my name is Frank Faustino
4. Whenever call
or apply
method is used, this
is explicitly defined 26:15
const ryan = new Person({firstName: 'Ryan', lastName: 'Hamblin'});
const sean = new Person({firstName: 'Sean', lastName: 'Chen'});
ryan.greet.call(sean); // "Hello my name is Sean Chen
sean.greet.apply(ryan, []); // "Hello my name is Ryan Hamblin
The call()
method calls a function with a given this
value and arguments provided individually. MDN webdocs
The apply()
method calls a function with a given this
value, and arguments provided as an array (or an array-like object). MDN webdocs
Closures 29:38
A closure is the combination of a function and the lexical environment within which that function was declared.
function initialize () { // ← 'initialize' function scope─────────────┐
var language = 'JavaScript'; // ← variable 'language' provides closure │
function shoutYourLang() { // ← 'shoutYourLang' function scope──────┐ │
alert(language); // ← alert points to 'language' │ │
}; // ←─────────────────────────────────────┘ │
}; // ←─────────────────────────────────────────┘
class
36:48
The class declaration creates a new class with a given name using prototype-based inheritance.
Syntax
class name [extends] {
// class body
}
class Person {
constructor(options) {
this.firstName = options.firstName;
this.lastName = options.lastName;
};
greet() {
console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
};
};
extends
41:40
The extends
keyword is used in class declarations or class expressions to create a class which is a child of another class.
Syntax
class ChildClass extends ParentClass { ... }
class Human {
constructor(options) {
this.type = options.type;
this.firstName = options.firstName;
this.lastName = options.lastName;
}
}
class Person extends Human {
constructor(options) {
super(options); // <-- passes arguments to parent class
}
greet() {
console.log(`My name is ${this.firstName} ${this.lastName}`);
}
}
const frank = new Person({
type: 'human',
firstName: 'Frank',
lastName: 'Faustino',
});
frank.greet(); // "My name is Frank Faustino"
console.log(frank); // Person { type: 'human', firstName: 'Frank', lastName: 'Faustino' }
console.log(frank.type); // human
get
45:28
The get
syntax binds an object property to a function that will be called when that property is looked up.
Syntax
{get prop() { ... } }
{get [expression]() { ... } }
// Defining a getter on new objects
var obj = {
log: ['test'],
get latest() {
if (this.log.length == 0) return undefined; // if empty check
return this.log[this.log.length - 1]; // returns just the last element 'test' of the array
}
}
console.log(obj.latest); // Will return "test".
// Using a computed property name (expression)
var exp = 'foo';
var obj = {
get [exp]() { return 'bar'; }
};
console.log(obj.foo); // "bar"
Callback Functions 47:40
A callback is a function _that is _passed into another function _as an _argument _to be _executed later. (Developers say you “call” a function when you execute a function, which is why callbacks are named callbacks).
// filter an array of numbers to get a list that’s lesser than five
// we're passing an anonymous function as a callback (num => num < 5)
const numbers = [3, 4, 10, 20]
const lesserThanFive = numbers.filter(num => num < 5)
// same code as above with named functions instead of anonymous
const numbers = [3, 4, 10, 20]
const getLessThanFive = num => num < 5
const lesserThanFive = numbers.filter(getLessThanFive) // <-- callback
Why use callbacks?
Callbacks are used in two different ways — in _synchronous _functions and _asynchronous _functions.
Callbacks in synchronous functions
If your code executes in a top to bottom, left to right_fashion, _sequentially, _waiting _until one code has _finished _before the next line begins, your code is synchronous. The filter()
example above is synchronous.
Callbacks in asynchronous functions
Asynchronous here means that, if JavaScript needs to wait for something to complete, it will execute the rest _of the tasks given to it _while waiting.
An example of an asynchronous function issetTimeout
. It takes in a callback function to execute at a later time:
// Calls the callback after 1 second
setTimeout(callback, 1000)
Let’s see howsetTimeout
works if you give JavaScript another task to complete:
const tenSecondsLater = () => console.log('10 seconds passed!')
setTimeout(tenSecondsLater, 10000)
console.log('Start!')
In the code above, JavaScript executessetTimeout
. Then, it waits for ten second and logs “10 seconds passed!”.
Meanwhile, while waiting forsetTimeout
to complete in 10 seconds, JavaScript executesconsole.log("Start!")
.
So, this is what you’ll see if you log the above code:
// What happens:
// > Start! (almost immediately)
// > 10 seconds passed! (after ten seconds)