Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: if "Object" is a function, how it can have methods?

Tags:

javascript

If I check the type of the Object object it says "function":

typeof Object === "function"

But we all know, that Object has multiple methods such as:

Object.create();
Object.freeze();
Object.seal();
Object.getPrototypeOf();
...

(check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)

My question: how is that possible? How a function is able to have methods? I always thought, that a method is a function that is the value of a property of an object.

Here we use it as an object:

Object.freeze();

and here we use it as a constructor function:

var myObj  = new Object();
var myObj2 = Object();

What is "Object" now? It seems it is both: function and object.

Is it a special case because these (Object, Array, String, Number) are the "native constructors"?

like image 284
Teemoh Avatar asked Jul 24 '26 21:07

Teemoh


2 Answers

A Function is a an object in Javascript and thus can both be called like a function AND can have properties (e.g. methods).

function f() {
    console.log("hello");
}

f.greeting = "goodbye";

f();                       // outputs "hello"
console.log(f.greeting);   // outputs "goodbye"

Note that functions also have built-in properties and methods such as .call(), .apply() and .length, .prototype, etc... See the description of the Function object on MDN for more info on the built in properties/methods.

Object itself is a constructor function that is meant to be used like this:

var x = new Object();

Though normally one will use the object literal syntax to declare a new object:

var x = {};

As a constructor function Object can both be called as a constructor (using new) and it can have properties/methods of its own.

My question: how is that possible? How a function is able to have methods? I always thought, that a method is a function that is the value of a property of an object.

This is how Javascript is designed. Functions are objects and can have properties/methods of their own.

Is it a special case because these (Object, Array, String, Number) are the "native constructors"?

This is not a special case. This is true for all functions. As my code example above shows, you can define your own functions and give them properties/methods.

like image 174
jfriend00 Avatar answered Jul 27 '26 10:07

jfriend00


A function is a number is a string is a boolean is an array is an object.

Okay, well, it's not that simple. But a function is an object and can have properties just like every other object in JavaScript:

var a = function() { return 10; };
a.foo = function() { return 20; };
console.log(a());     // 10
console.log(a.foo()); // 20
like image 38
tckmn Avatar answered Jul 27 '26 09:07

tckmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!