- A reserved keyword in JavaScript.
- The purpose for 'this' is that it allows us to re-use functions with different context.
- The value of 'this' is usually determined by how a function is invoked. ('execution context').
- When a function is called, 2 special keywords are given to that funciton: arguments and this
- Every time a function is run, the keyword 'this' is defined for that function.
- Can be determined using four rules (global/window binding, object/implicit binding, explicit binding, new binding).
- When 'this' is not inside of a declared object, it refers to the global object, typically 'window'
console.log(this); // window
- returning 'this' inside of a function will still be the global object
- 'this' is still not inside of a declared object
function whatIsThis() {
return this;
}
whatIsThis(); // window
- it's very bad practice to declare global variables inside of a function
function variablesInThis() {
this.person = 'Boolean Brandon';
}
variablesInThis() // 'this' inside the function is still the window
// person is now a global variable assigned to 'Boolean Brandon' even though it was assigned inside a function
- "use strict" when typed at the top of a file, will throw an error if you try to declare a global variable inside a function
- when the keyword 'this' is inside of a declared object, its value will always be the closest parent object
const person = {
firstName: 'Brian',
sayHi: function() {
return "Hi " + this.firstName;
}
}
person.sayHi();
// this refers to person;
- The keyword 'this' is only re-defined when a function is run! In the next example the keyword 'this' still refers to the global object.
const person = {
firstName: 'James',
determineContext: this;
}
person.determineContext; // window
- Nested Objects
const person = {
firstName: 'Gray',
sayHi: function() {
return "hi " + this.firstName;
},
dog: {
firstName: 'Winnie',
sayHello: function() {
return 'hello ' + this.firstName;
}
}
};
person.sayHi(); // "hi Gray";
person.dog.sayHello(); // "hello Winnie"
// always look to the left of the dot, thats usually what 'this' is referring to
- Choose what we want to the context of 'this' to be using call, apply, or bind
- call, apply, and bind can only be invoked on functions
- call, apply, and bind have precedence over the first 2 rules
- call and apply will invoke the function that they are called on immediately, whereas bind will return a new function definition with the value of the keyword this explicitly set
- call and bind accept an infinite number of parameters, whereas apply only takes in 2 parameters
- call can be used to bind 'this', when defined in a stand alone function, to an object that it is invoked on. '
const sayName = function() {
console.log('My name is ' + this.name);
}
const gray = {
name: 'Gray',
age: 32
};
const alex = {
name: 'Alex',
age: 38
}
sayName.call(gray); // 'My name is Gray'
sayName.call(alex); // 'My name is Alex'
- Call can also enable you to use a funciton defined in one object on another object.
const kurt = {
firstName: 'Kurt',
sayHi: function() {
return 'Hi ' + this.firstName;
}
}
const kevin = {
firstName: 'Kevin'
}
kurt.sayHi(); // Hi Kurt
kurt.sayHi.call(kevin); // Hi Kevin
- The first argument passed in to call explicitely states what to bind the keyword 'this' to. Every argument after that are the arguments that are passed to the actual function being invoked.
- Apply is the exact same as call except call passes arguments to the function as separate values and apply passes arguments to the function as an array.
function addNumbers(a, b, c) {
return this.firstName + ' just calculated ' + (a + b + c);
}
const tom = {
firstName: 'Tom'
}
addNumbers.call(tom, 1, 2, 3); // Tom just calculated 6
addNumbers.apply(tom, [1, 2, 3]); // Tom just calculated 6
'* when a function does not accept an array, apply will spread out values in an array for us!
function sumValues(a,b,c) {
return a+b+c;
}
var values = [4, 2, 1];
sumValues(values); // undefined
sumValues.apply(this, [4, 2, 1]); // 7
- Bind works just like Call, but instead of immediately invoking the function, it returns a new function with the keyword 'this' set to the value we pass as the first parameter when calling bind.
- Bind can be useful when we do not yet know all of the arguments that will be passed to a funciton.
- We do not need to know all of the arguments to a funciton when we call bind, only what we want the value of the keyword 'this' to be.
function addNumbers(a,b,c) {
return this.firstName + " just calculated " + (a+b+c);
}
const timf = {
firstName: "Timf"
}
const timfCalc = addNumbers.bind(timf, 1, 2, 3); // function(){}...
timfCalc(); // Timf just calculated 6
- very commonly we lose the context of 'this', especially in functions that we do not want to execute right away.
const cody = {
firstName: 'Cody',
sayHi: function() {
setTimeout(function() {
console.log('hi ' + this.firstName;
}, 1000);
}
}
// the keyword this inside setTimeout actually refers to the global object, since setTimeout is called at a later point in time, the object that it is attached to is the window. The context in which setTimeout is executed is the global context.
// we could use call or apply to set the keyword 'this', but we dont want to call the function until a later point in time. So we use bind.
const cody = {
firstName: 'Cody',
sayHi: function() {
setTimeout(function() {
console.log('hi ' + this.firstName;
}.bind(this), 1000);
}
}
// using .bind(this) on setTimeout will bind the keyword 'this' to the parent object which is cody.
- we can set the context of the keyword 'this' using the 'new' keyword.
- when the 'new' keyword is used, a new object is created. The new keyword is used with a function and inside the function definition, the keyword 'this' will refer to the new object that is created.
- when the new keyword is used, an implicit return 'this' is added to the funciton which uses it.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const dennis = new Person("Dennis", "Miller");
dennis.firstName; // "Dennis"
dennis.lastName; // "Miller"
- The keyword 'this' is a reserved keyword in JavaScript and its value is determined at execution.
- It is either set using the global context, object binding, explicit binding, or the new keyword.
- When set in the global context in a function, it is either the global object (window if in the browswer) or undefined (if we are using "strict mode").
- When the keyword this is inside of a declared object, its value will be the closest parent object.
- When we lose the value of the keyword 'this' that we want, we can explicitly set the value of the keyword 'this' by using call, apply, or bind.
- We can also use the 'new' keyword to set the context of 'this'. When the 'new' keyword is used, the value of 'this' is set to be an empty object and is implicitly returned from the function that is invoked with the 'new' keyword.