I am a newbie in javascript, and was studying about constructor functions and the new
keyword. After omitting new
intentionally, it is causing some problems, and I am not able to understand exactly why is it happening.
let Fruit = function (person, color) {
this.person = person;
this.color = color;
this.displayInfo = function () {
console.log(this.person + " is " + this.color);
}
}
let altFruit = function (person, color) {
this.person = person;
this.color = color;
}
let a1 = altFruit('Banana', 'Yellow'); //new keyword not written
let f1 = new Fruit('Orange', 'orange');
let aFunction = f1.displayInfo;
aFunction();
I didn't write new
when initialising object a1
. I stored the function f1.displayinfo
in a variable, and then called it. Expected output was undefined is undefined
, but instead I got Banana is Yellow
.
It is really baffling to me because aFunction
has nothing to do with altFruit
constructor function or a1
. Also, even after seeing many tutorials, I still don't really understand what is the exact meaning of new
because this weird output is happening only when I omit it.
Value of this
depends on how the function is called.
In non-strict mode, when you call the altFruit
function without the new
keyword, this
inside it will refer to the global window
object. So,
this.person = person;
will add person
property on the global window
object. (you can test this by logging window.person
on the console at the end of your code).
When you call aFunction
, in non-strict mode, value of this
inside displayInfo
function will refer to the global window
object.
In short, your code is adding and reading properties to and from the global window
object, respectively.
new
operator is used to create instances of user-defined object types (like Fruit
) or built-in object types (like Array
, Date
, etc).
When you call new Fruit(...)
, new
operator will do the following things:
Create a new object
Add __proto__
property on the newly created object that points to Fruit.prototype
object.
Point this
inside the Fruit
constructor to the newly created object.
Return the newly created object from the Fruit
constructor function.
For more details, see: MDN: new operator