I am new to JavaScript and I am following Douglas Crockford's book, The Good Parts.
It says:
Every function object is also created with a
prototypeproperty. Its value is an object with aconstructorproperty whose value is the function. This is distinct from the hidden link toFunction.prototype.
I understand that function objects are linked to Function.prototype, but what does the above line mean?
Can someone simplify it for me?
2 Answers 2
Every function object is also created with a
prototypeproperty.
var fn = function() { };
fn.hasOwnProperty("prototype"); // true
That is, for every function in JavaScript, each one has a prototype property, just like any other JavaScript object.
Its value is an object with a constructor property whose value is the function.
The object that prototype points to has a constructor property which points to the original function.
fn.prototype.constructor === fn // true;
That is, you can derive the constructor function from a constructed object by looking at obj.prototype.constructor (unless it's been overwritten).
This is distinct from the hidden link to
Function.prototype
The function you create's prototype object is not the same as the Function's prototype.
fn.prototype != Function.prototype // true
That is, if you augment Function.prototype, then the methods will be available on function references. If you augment your function's prototype, then those methods will be available on constructed objects using that constructor.
Comments
It means that a function is an instance of a class named Function.
An instance is a reproduction of a model, a class, that conveys methods and attributes.