0

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.

4
  • 1
    It's a static method. Commented Sep 18, 2018 at 5:09
  • 1
    A constructor is just a function, and all functions are objects. All objects can have methods placed on them. Ergo, a constructor can have methods. Commented Sep 18, 2018 at 5:09
  • What is confusing? in most object oriented languages, classes can have class methods. Commented Sep 18, 2018 at 5:09
  • I am guessing the constructor looks like this: function Object(){//constructor} and the methods like create() would be like Object.create = function(){//native code for create}? Commented Sep 18, 2018 at 5:24

1 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

YES, YES, YES! That is what I was wondering, how it was done the earlier way. I understand now. I knew the create() method for example was not part of its prototype. I appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.