Is it possible to break down the following code (especially the new
keyword) into simpler code (so I can understand what's going on)?:
function F() {
this.color = 'red';
this.printNumber = function printNumber() {
console.log(5);
};
}
let o = new F();
console.log(o);
Here is my attempt:
I thought I was onto a winner when I was told that let o = new F();
is the same as let o = F.call({})
but I can see on the console that the first additionally gives the empty object a constructor
property set to the constructor function.
Is it very important that the new object has a constructor property set to the constructor function? I know that this constructor function would be considered a method and the this
in there would refer to this object as a whole. Which leads me to think that the new
works by:
- Instantly creating an object that has a constructor property set to the constructor function.
- Executing the constructor property (a method) so that the new object looks like:
{
color: "red",
printNumber: printNumber,
constructor: F
//as it is an instance of the inbuilt Object constructor function, it has all the properties/methods of an object
}