What is __proto__?
Every object in javascript has a __proto__ property.
The __proto__ property points to object that this object inherits from.
By default an object non-function points to Object.prototype.
(Object.prototype is basically the root object, and its __proto__ is null) i.e. (Object.prototype.__proto__) is null.
By default an function object points to Function.prototype (Function.prototype this is where function inherits methods like .apply(), .call(), etc...)
Function.prototype__proto__ points to Object.prototype.
Invoking a function as a constructor
This basically just means calling a function using the keyword new.
When you do that the __proto__ of object created becomes the functions ".prototype" which by default which will be Object.prototype.
NOTE this is not the same as the function object's __proto__ which is Function.prototype.
I.e. by default:
var y = function(){}
y.__proto__ = Function.prototype
y.prototype = Object.prototype
What is .prototype?
By setting .prototype on a function object which is going to be invoked as a constructor, we are basically setting the __proto__ property for the object that is goingto be created using this function.
To Summarize
var x = {};
// x.__proto__ = Object.prototype
var f = function(){};
// f.__proto__ = Function.prototype
// f.prototype = Object.prototype
f.prototype = x;
// f.__proto__ = Function.prototype
// f.prototype = x (duh!)
var y = new f();
// y.__proto__ = x;
No comments:
Post a Comment