Okay. Here's the thing. There are some concepts in JS that seem really convoluted at the start, but are actually really straightforward. Let's have a look at a few of them.
1) function.prototype
property
When you define a function, the JS engine creates an anonymous object and binds the two using property names prototype
and constructor
as follows:
function foo(){}
/* Performed by JS engine internally */
// foo.prototype = {};
// foo.prototype.constructor = foo;
Therefore, only functions have .prototype
.
The .prototype
is used only and only when the function is invoked using the new
operator.
2) References
In JS, references can be used to pass along a variable, without creating a duplicate of it. Perhaps an example might help here:
var a = 1;
var b = { val: 1 };
var c = { val: 1 };
var x;
/*variable cloned*/
x = a;
x++;
console.log(a); // 1
console.log(x); // 2
/*variable refernced*/
x = b;
x.val++;
console.log(b); // { val: 2 }
console.log(x); // { val: 2 }
/*variable cloned*/
x = c.val;
x++;
console.log(c); // { val: 1 }
console.log(x); // 2
3) object.__proto__
property
Any object created by invoking a function with the new
keyword, like var x = new foo();
, will have a __proto__
property on it that is the object referenced by its constructor function's .prototype
property. Re-assigning foo.prototype
to somethings else will not affect objects that have already been created.
In other words,
function foo(){}
// foo.prototype = {};
// foo.prototype.constructor = foo;
var x = new foo();
console.log(x.__proto__ === foo.prototype); // true
Also, when you create an object like var x = {};
, it is the exact same thing as:
var x = new Object();
Therefore, x.__proto__
is the object referenced by Object.protoype
.
Conclusion
How does all this add up?
foo.prototype
acts as a "blueprint" for the objects created using the function foo
.
When we do create an object x = new foo()
, JS engine stores a reference (link) to "the blueprint that was used to make x
" as the __proto__
property.
When I do getPrototypeOf() I get the expected output, but when I try to use the prototype property I get undefined. Cant figure out the reason.
Object.getPrototypeOf(...)
returns the __proto__
property, not prototype
.
Also for line 5 return value is function(). Can some please explain does this say ? I expected an Object to be returned.
In JS, all data types have an associated "Wrapper" function.
Similar to how x = {}
is the same as x = new Object()
, doing function b(){}
is the same as b = new Function()
since b
was created invoking a function using new
, it has a __proto__
property, that is the object referenecd by its constructor function's prototype. In this case, Function.prototype
, which is also Function.
Still confused? I'd recommend having a good long read at http://www.javascripttutorial.net/