Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the function constructor in Node.js?

In the browser (chrome at least) functions are instances of Function

setTimeout instanceof Function
// true

However in node, they are not

setTimeout instanceof Function
// false

So what is setTimeout's constructor if not Function?

like image 582
Aakil Fernandes Avatar asked Nov 05 '16 23:11

Aakil Fernandes


People also ask

What is constructor in Nodejs?

The constructor method is a special method of a class for creating and initializing an object instance of that class. Note: This page introduces the constructor syntax. For the constructor property present on all objects, see Object. prototype.

What is the function of constructor !?

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

What is a constructor function in class?

A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have exact same name as the class and it does not have any return type at all, not even void.

What is the difference between function and constructor in JavaScript?

Using functions for creating objects is fairly common in Javascript, so Javascript provides shortcut that lets you write functions for creating objects. These special functions are called Constructor functions. Constructors are functions that lets you populate the object which you need to create.


1 Answers

It seems the constructor is Function, but the one from another realm.

If you run this code

console.log(Object.getOwnPropertyNames(setTimeout.constructor.prototype));

you get an array with the typical Function.prototype methods like call, apply and bind.

So I guess it's somewhat analogous to what happens in web browsers when you borrow setTimeout from an iframe:

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var win = iframe.contentWindow;
console.log(win.setTimeout instanceof Function);     // false
console.log(win.setTimeout instanceof win.Function); // true
like image 96
Oriol Avatar answered Sep 22 '22 21:09

Oriol