JavaScript Prototype Instantiation

by jonpress

In JavaScript, functions can be used in two ways; they can be simply called or they can be instantiated. When you call a function, it will simply run the code inside it and possibly return some value – When you instantiate a function, the JavaScript engine will first create a new object (a clone of that function’s prototype) and then will call that function using the newly created object as the context for the ‘this’ keyword.

Function prototypes are essentially empty objects by default – You can add properties to the prototype object using the Function.prototype property. Here is an example of how to add properties to a function’s prototype:

var Fun = function() {
    this.prop = 'This is a property of a Fun instance';
}

// Adding a 'foo' property to the 'Fun' function’s prototype
Fun.prototype.foo = function() {
    return 'foo';
}

var fun = new Fun(); // fun is an object with a 'foo' property which is a function

When ‘new Fun()’ is called, the JavaScript engine first creates a clone of the function’s prototype object which essentially looks like this: {foo: function() {return ‘foo’;}}; then it executes the Fun function using the cloned object as the ‘this’ reference – Because of that, properties added to ‘this’ within the function body can overwrite those defined in the prototype.

About these ads