Search code examples
javascriptlanguage-lawyer

What is window.constructor and global.constructor native function?


What is the use of this function? I can't find any information about it.

I've tried in Firefox:

window.constructor()
// TypeError: Illegal constructor

new window.constructor()
// TypeError: Illegal constructor

in NodeJS it returns an empty object:

constructor()
// {}

For reference if someone what to know why I need to know this: I have an issue with my Scheme interpreter when I use code like this in NodeJS:

(define-class Foo (constructor (lambda (self) (print "<new>"))))

The second argument should be the parent object but it's missing. The problem is in NodeJS constructor() returns function if you use code like this:

constructor(function foo() { })
// [Function: foo]

So my code that checks if the parent is a function will fail in NodeJS.

I'm not sure how to fix my define-class but I just want to know what constructor() is and if it's documented somewhere.


Solution

  • Node and browsers each uses its own implementation of ECMAScript (also known as the ECMA262 Standard), which has no definition for any symbol called Window. That interface is defined by the HTML Standard, which also doesn't define the constructor property.

    The global object is defined, however, by ECMA262 (emphasis mine):

    The global object:

    • is created before control enters any execution context.
    • does not have a [[Construct]] internal method; it cannot be used as a constructor with the new operator.
    • does not have a [[Call]] internal method; it cannot be invoked as a function.
    • has a [[Prototype]] internal slot whose value is host-defined.
    • may have host-defined properties in addition to the properties defined in this specification. This may include a property whose value is the global object itself.

    ...where host-defined basically means "defined by an external specification or implementation" (such as the HTML Standard or Node).

    In other words, global.constructor/window.constructor is an implementation-dependent detail.