By utilizing the new
keyword before a function, it ensures that the function is invoked with a fresh empty object assigned to the this
value, even if .bind()
was previously applied (essentially disregarding any prior this
setting).
In cases where your function does not have a return statement and the new
keyword is used, the default behavior is for the function to return the updated this
value after execution. In this scenario of calling AgedPerson
, the this
context is initialized as an empty object {}
due to the presence of new
. As the function progresses, the name
property is added to this object and ultimately returned implicitly, resulting in {name: "John"}
.
The use of .bind()
becomes relevant when the function is called through other methods like ()
, or with .call()
and .apply()
, but not applicable when employing new
. For example:
"use strict";
const person = function(name) {
this.name = name;
}
const age = { age: 128 };
const agedPerson = person.bind(age)
agedPerson("John"); // modifies the age object by reference
console.log(age); // { age: 128, name: "John" }