I'm discerning the famous JS's extend function:
function extend(parent, child) {
var F = new Function();
F.prototype = parent.prototype;
child.prototype = new F();
//child.prototype.constructor = Child
}
I've commented out the line where the constructor property is overridden. If I create the objects in the following way:
var p = function p() {this.parent = true};
var c = function c() {this.child = true};
extend(p, c);
console.log((new c()).constructor); //outputs reference to `p` constructor, why?
My question is why the constructor references var p = function p() {this.parent = true}; instead of anonymous function that variable F points to? The manual on constructor property states that constructor property returns a reference to the Object function that created the instance's prototype and the instance prototype new F() was created by anonymous function. So why does it point to the other thing?
Update
Is the following assumption I've made based on HMR's answer correct?
When a new function is created, JS engine creates new empty object and sets prototype proprety of the function to point to this newly created object. Then JS engine adds a constructor property to this object pointing to the created function.
So now to my case. When var F = new Function() JS engine:
1) creates new F function
2) creates new object (let it be oF)
3) sets prototype F.prototype = oF
4) sets constructor oF.constructor = F
The same goes for function p which has its prototype oP with a constructor property set to function p. As we remember, F.prototype points to oF but after we execute the following line F.prototype = parent.prototype it is now points to oP. Then when we access (new c()).constructor property new c() object doesn't have it so JS engine starts looking backwards on prototypes and finds the property on oP pointing to function p - and this is excatly what I get.