
This, Bind, Apply, Call
The best way to talk about how these functions work is by starting with the this keyword.
This
In JavaScript this refers to the object in which it is associated. The code below will log what this is referencing.
console.log('Top level:', this);
const today = new Date();
const data = {
day: today.getDay(),
date: today.getDate(),
month: today.getMonth(),
year: today.getFullYear(),
getFullDate:function () {
const days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri','Sat'];
const months = ['Jan', 'Feb', 'Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'];
console.log('In the object:', this);
return `${days[this.day]} ${months[this.month]} ${this.date} ${this.year}`;
}
};
data.getFullDate();
//Top level: Window {parent: Window, opener: null, top: Window, length: 0, frames: Window}
//In the object: {day: 1, date: 25, month: 4, year: 2020, getFullDate: ƒ}It is important to note that arrow functions, () => {}, do not have their own this keyword. They inherit it from the parent scope. In the example below this is attached to the global scope.
const nums = {
num: 1,
numFunc: () => {
console.log(this);
}
};
nums.numFunc();
//Window {parent: Window, opener: null, top: Window, length: 0, frames: Window}Apply, Call, Bind
The apply method calls another function with a specified this and arguments in the form of an array.
const today = {
getFullDate:function (day,month,date) {
return `${this.greeting} ${day} ${month} ${date} ${this.year}`;
}
};
const intro = {
greeting: 'Hello! Today is ',
year: 2020
};
today.getFullDate.apply(intro, ['Mon', 'May', 25]);
//intro becomes the this in reference
//['Mon', 'May', 25] are the argumentsThe call method invokes another function, similar to the apply, with a specified this and arguments that are comma-separated.
const thisDate = {
getFullDate:function (day,month,date) {
return `${this.greeting} ${day} ${month} ${date} ${this.year}`;
}
};
const greetThem = {
greeting: 'Hello! Today is ',
year: 2020
};
thisDate.getFullDate.call(greetThem, 'Mon', 'May', 25);
//greetThem becomes the this in reference
//'Mon', 'May', 25 are the argumentsLastly, the bind method creates a new function that will have its this value set to a given value. Bind also accepts a comma-separated list of arguments.
let user = {
firstName: 'Morgan',
lastName: 'Freeman'
};
function greeting(message){
return `${message}, ${this.firstName} ${this.lastName}!`;
}
let greetUser = greeting.bind(user);
greetUser('Welcome');
//"Welcome, Morgan Freeman!"As always play with the code to see how things work.