简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM