- Explain the difference between a function and a method
- Create basic objects with methods
- Explain what the
this
keyword is - Use
call
/bind
to mantainthis
context - Use es6 arrow functions to preserve
this
context
-
Explain the difference between a function and a method. What is an example of a method you use regularly?
Your answer...
-
Label each invokation bellow as either a
function
ormethod
invocation:Number.parseFloat('16.60')
isNaN(0)
['Hello', 'World'].join(', ')
({ ten: function() { return 10; } }).ten()
var obj = {} obj.myFunction = function() { return new Date().toString() }; obj.myFunction()
var otherFunction = obj.myFunction otherFunction()
Your answer...
-
Pracice creating basic objects with methods
In a scratch js file or repl.it, code an object that represents a party!
var party = { // fill in some details about the party here snacks: [...] }
Now add a
printSnacks
method to your party object. Callparty.printSnacks()
and try running your code.
Lets test out 5 scenarios using this
console.log(this)
function getThis() {
console.log(this)
console.log('Is global:', this === window)
}
getThis()
var party = {
host: 'Roger',
snacks: ['cheetos', 'beer'],
printSnacks: function() {
console.log(this, this === window)
}
}
party.printSnacks()
var party = {
host: 'Roger',
snacks: ['cheetos', 'beer'],
printSnacks: function() {
function innerFunction() {
console.log(this, this === party)
}
innerFunction()
}
}
party.printSnacks()
var party = {
host: 'Roger',
snacks: ['cheetos', 'beer'],
printSnacks: function() {
console.log(this.snacks)
}
}
setTimeout(party.printSnacks, 200)
What is this
refering to in each of the examples above?
In your own words, write a definition for the this
keyword in javascript
-
What are
call
,bind
, andapply
used for?Your answer...
-
How can we fix cases 4 & 5 from above to use the correct context (we want
this === party
)?Your answer...