please explain this detail about the prototype property and function constructor in javascript

128 Views Asked by At

I'm reading a great book called 'Javascript Enlightenment' by Cody Lindley. In the chapter that covers the prototype property it discusses how a function instance is always given a prototype property...easy enough to understand. The bold text in the following excerpt is what I don't understand however:

Prototype is standard on all Function() instances. All functions are created from a Function() constructor, even if you do not directly invoke the Function() constructor

(e.g. var add = new Function('x', 'y', 'return x + z');)

and instead use the literal notation

(e.g. var add = function(x,y){return x + z};).

When a function instance is created, it is always given a prototype property, which is an empty object. Below, we define a function called myFunction, then we access the prototype property, which is simply an empty object.

<!DOCTYPE html><html lang="en"><body><script>
var myFunction = function() {};
console.log(myFunction.prototype); // logs object{}
console.log(typeof myFunction.prototype); // logs 'object'
</script></body></html>

Make sure you completely understand that the prototype property is coming from the Function() constructor. It is only once we intend to use our function as a user-defined constructor function that the prototype property is leveraged, but this does not change the fact that the Function() constructor gives each instance a prototype property.

Here are my questions about the bold text: 1. why is the prototype object empty? I thought prototype was supposed to have some properties and methods inside of it for all native objects. 2. I can't figure out at all what it means that prototype is leveraged only once you intend to use the function as a user defined constructor function. Does this mean that the prototype chain is only accessible when a function is user defined?

1

There are 1 best solutions below

0
On
  1. The prototype property object is empty because nothing has been assigned to it, but it still exists for every function, that's just how javascript was written.
  2. You will only use the prototype property if your writing object-oriented javascript. Here's a quick example:

    function myFunction() {this.a=1; this.b=2;}
    myFunction.prototype.myMemberFunction = function() {return this.a + this.b;}
    var f = new myFunction();
    
    // Now you can call the member function like this:
    alert(f.myMemberFunction());
    

f is now an object in which you have access to all member variables, functions, etc.