“this” keyword:
In JavaScript, the
this
keyword is used to indicate the context of a function. Thethis
keyword can refer to different objects depending on how the function is called. It answers the question of where it should get some value or data from.
In this post, we'll explore the four types of bindings in JavaScript and provide examples to illustrate each type.
Bindings in JavaScript:
- Bindings establish the relationship between identifiers (variables, functions) and their values within the scope of a program.
- They dictate how variables and functions are accessed and manipulated throughout the code.
(1) Default Binding
Default binding is the binding that occurs when a function is called without any arguments. In this case, the function is bound to the global object.
Here’s an example:
function greet(name) {
console.log('Hello, ' + name + '!');
}
greet(); // Output: Hello, world!
In this example, the greet()
function is called without any arguments, so it is bound to the global object.
(2) Implicit Binding
Implicit binding occurs when a function is called using dot notation. In this case, the this
keyword is implicitly bound to the object the function is being called from.
Here's an example:
function alert(name) {
console.log(this.name + ' is calling');
}
const obj = {
name: 'Kingsley',
alert: alert
};
obj.alert(); // Output: Kingsley is calling
In this example, the alert()
function is called on the obj
object using dot notation, so the this
keyword is implicitly bound to obj
.
(3) Explicit Binding
Explicit binding occurs when you use the call()
,apply()
or bind()
methods to explicitly bind a function to an object.
Here's an example of explicit binding using call()
:
function greet(name) {
console.log('Hello, ' + name + '!');
}
const person = {
name: 'Alice',
greet: function(name) {
greet.call(this, name);
}
};
person.greet(); // Output: Hello, Alice!
In this example, the greet()
function is called on the person
object using the call()
method, so the this
keyword is bound to person
.
(4) Constructor Call Binding (new)
Constructor call binding occurs when a function is called with the new
keyword. In this case, a new object is created and set as the this binding for that function call.
Here's an example:
function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice.name); // Output: Alice
In this example, the Person()
function is called with the new
keyword, so a new object is created and set as the this
binding for the Person
function call.
How the object creation with the ‘new’ keyword is done?
When you create a new object using the new
keyword with the constructor function, the following steps occur:
- A new empty object is created.
- The newly created object is linked to the prototype of the constructor function.
- The constructor function is executed with the
this
keyword bound to the newly created object. - Properties and methods are added to the object using
this
. - The constructor function implicitly returns the newly created object.
For example:
function Person() {
var name = "Andrew";
this.age = 50;
function sayHi() {
console.log("Hello");
}
this.sayBye = () => {
console.log("Bye");
}
}
// Create a new object using the Person constructor
var andrew = new Person();
// Access and log the properties and methods of the andrew object
console.log(andrew.age); // Output: 50
andrew.sayBye(); // Output: bye
console.log(andrew.name); // Output: undefined
andrew.sayHi(); // Error: sayHi is not a function
The andrew
object will have a property age
with the value 50
, and a method sayBye
which logs "Bye" to the console when called.
However, the name
variable defined inside the constructor function is not accessible from outside, as it is a local variable within the function scope and not attached to the this
object. Similarly, the sayHi
function is not added to the andrew
object because it is defined within the constructor function's scope and is not assigned to this
.
Therefore, andrew
object will not have any property or method related to name
or sayHi
.
Hard Binding:
Hard binding falls under the category of “explicit binding”. The hard binding occurs when a function is called multiple times and the this
binding is locked to a specific object.
It means that even if you were to pass around that function multiple times to new variables (currying), every invocation will use the same context because it has been locked (explicitly bound) to that object.
Here's an example of hard binding:
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
In this example, the function bar
is hard-bound to the object myObj
, ensuring that its this
context always refers to myObj
. This prevents the this
context from being overridden, even when the function is called with a different context.
Hard binding effectively locks the context of a function call to a specific object, essentially making the function behave like a method of that object.
In summary, the
this
keyword in JavaScript can refer to different objects depending on how the function is called. Understanding bindings and the ‘this’ keyword is essential for writing robust and flexible JavaScript code.