Context - Falicer/Project_Tech_2021 GitHub Wiki
Context or also known as this
is the reference to an object that the owner is of the code or function being executed/used. Everything needs context, without context no one would understand what's being talked about.
Types of Context
- Global context
- Function context
- Call, Apply, Bind (CAB)
- Arrow functions (ES6)
Global context
Outside the use of a function the global execution of this
will be seen as the window object.
So how that would look like is kinda like this:
var a = 15;
console.log(this.a);
// => 15
console.log(window.a);
// => 15
Function context
In the use of functions this
is referenced to the object the function is executed in, for example:
function fx () {
return this;
}
var obj = {
method: function () {
return this;
}
};
var x_obj = {
y_obj: {
method: function () {
return this;
}
}
};
console.log(fx() === window);
// => True
console.log(obj.method() === window);
// => False
console.log(obj.method() === obj);
// => True
console.log(x_obj.y_obj.method() === x_obj)
// => False
True
— We are still in a global context.False
— Function is called as a method of an object.True
— Function is called as a method of an object.False
— Function is called as a method of object y_obj, sothis
is its context.
Call, Apply, Bind
These methods allow us to execute any function in any desired context, for example:
var bar = "xo xo";
var foo = {
bar: "lorem ipsum"
};
function test () {
return this.bar;
}
console.log(test());
// => xo xo
console.log(test.call(foo));
// => lorem ipsum
console.log(test.apply(foo));
// => lorem ipsum
xo xo
— We called test in a global context.lorem ipsum
— By using call, we call the test in context of foo.lorem ipsum
— By using apply, we call the test in context of foo.
Those two methods allow you to execute the function in any desired context.
apply
lets you invoke the function with arguments as an array whereas, call required the listed parameters explicitly.
Arrow Functions (ES6)
Arrow Functions are a new thing from ES6, as handy as they can be they work differently from regular functions in terms of context, for example:
var foo = (() => this);
console.log(foo() === window);
// => True
When using arrow functions, this
retains the value of the context.
var obj = {method: () => this};
var sec_obj = {
method: function() {
return this;
}
};
console.log(obj.method() === obj);
// => False
console.log(obj.method() === window);
// => True
console.log(sec_obj.method() === sec_obj);
// => True
The difference is that using arrow functions you already work within the window context, as arrow functions are always bound to this
so they can't be used as a constructor.