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
?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With