Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding function objects in JavaScript

Tags:

javascript

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 prototype property. Its value is an object with a constructor property whose value is the function. This is distinct from the hidden link to Function.prototype.

I understand that function objects are linked to Function.prototype, but what does the above line mean?

Can someone simplify it for me?

like image 811
poorvank Avatar asked Sep 20 '13 11:09

poorvank


People also ask

What are function objects in JavaScript?

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. For more examples and explanations, see the JavaScript guide about functions.

What are functions and objects?

An object is a collection of functions and data. A function is a collection of commands and data. When a bunch of functions work together to perform a certain task we may call this community of functionality an object.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

Every function object is also created with a prototype property.

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.

like image 193
alex Avatar answered Nov 03 '22 00:11

alex