Hayden
Hayden

Reputation: 857

How can you call methods on Object if it is a constructor?

The Object object is defined as a constructor. However, I am able to call methods on it like Object.create(), Object.freeze(), Object.assign(), etc... I can also create a new object by typing "var foo = new Object()".

So if Object is a constructor, how am I able to call methods directly on it?

That has always confused me.

Upvotes: 0

Views: 51

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

Constructors can have properties themselves, too. In modern syntax, these are called static methods. For example:

class Foo {
  static fooRelatedFn() {
    console.log('foo related function running');
  }
  constructor() {
    this.bar = 'bar';
  }
}

Foo.fooRelatedFn();
const foo = new Foo();
console.log(foo.bar);

The same thing can be done using conventional syntax, simply by assigning to a property of the constructor:

function Foo() {
  this.bar = 'bar';
}
Foo.fooRelatedFn = function() {
  console.log('foo related function running');
}

Foo.fooRelatedFn();
const foo = new Foo();
console.log(foo.bar);

Upvotes: 4

Related Questions