44
loading...
This website collects cookies to deliver better user experience
this
in your code, it automatically resolves to an object or scope depending on the context at which is was defined.this
call can refer to? Additionally, how can we use that information to find out which object a this
call will resolve to? Let's find out!this
keyword simply points to an object which it is bound to. In simple terms, it answers the question of where it should get some value or data from:function alert() {
console.log(this.name + ' is calling');
}
this
keyword is simply referring to an object to which it is bound to access the "name" property from it.this
is referring to?this
behavior.this
reference is a standalone function, then that function is bound to the global object.function alert() {
console.log(this.name + ' is calling');
}
const name = 'Kingsley';
alert(); // Kingsley is calling
name()
is a standalone, unattached function. As per the rule, it is bound to the global scope. Hence, the this.name reference resolves to the global variable const name = 'Kingsley'.name()
were to be defined in strict mode as so:function alert() {
'use strict';
console.log(this.name + ' is calling');
}
const name = 'Kingsley';
alert(); // TypeError: `this` is `undefined`
function alert() {
console.log(this.age + ' years old');
}
const myObj = {
age: 22,
alert: alert
}
myObj.alert() // 22 years old
function alert() {
console.log(this.age + ' years old');
}
const myObj = {
age: 22,
alert: alert,
nestedObj: {
age: 26,
alert: alert
}
}
myObj.nestedObj.alert(); // 26 years old
alert
is ultimately being called from nestedObj, this
is implicitly bound to nestedObj
instead of myObj
.function alert() {
console.log(this.age + ' years old');
}
const myObj = {
age: 22,
alert: alert,
nestedObj: {
age: 26,
alert: alert
}
}
myObj.alert(); // `this` is bound to `myObj` -- 22 years old
myObj.nestedObj.alert(); // `this` is bound to `nestedObj` -- 26 years old
call()
and apply()
.[[Prototype]]
mechanism.call()
on that function and pass in the context object as parameter:function alert() {
console.log(this.age + ' years old');
}
const myObj = {
age: 22
}
alert.call(myObj); // 22 years old
function alert() {
console.log(this.age);
}
const myObj = {
age: 22
};
const bar = function() {
alert.call(myObj);
};
bar(); // 22
setTimeout(bar, 100); // 22
// a hard-bound `bar` can no longer have its `this` context overridden
bar.call(window); // still 22
new
binding which also accentuates the unusual behaviour of JavaScript in comparison to other class-based languages.new
keyword in front of it, otherwise known as a constructor call, the following things occur:function giveAge(age) {
this.age = age;
}
const bar = new giveAge(22);
console.log(bar.age); // 22
this
reference.P/S: If you are learning JavaScript, I created an eBook which teaches 50 topics in JavaScript with hand-drawn digital notes. Check it out here