Object vs Class vs Function

Sean Bone提出了一个问题:Object vs Class vs Function,或许与您遇到的问题类似。

回答者CommunityAadit M Shah给出了该问题的处理方式:

As you must already be aware by now there are no classes in JavaScript. Instead functions in JavaScript may be made to behave like constructors by preceding a function call with the new keyword. This is known as the constructor pattern.

In JavaScript everything is an object except for the primitive data types (boolean, number and string), and undefined. On the other hand null is actually an object reference even though you may believe at first otherwise. This is the reason typeof null returns "object".

Functions in JavaScript are similar to functables in Lua (i.e. they are callable objects). Hence a function can be used in place of an object. Similarly arrays are also objects in JavaScript. On the other hand objects can be thought of as associative arrays.

The most important point however is that there are no classes in JavaScript because JavaScript is a prototypal object oriented language. This means that objects in JavaScript directly inherit from other objects. Hence we don't need classes. All we need is a way to create and extend objects.

Read the following thread to learn more about prototypal inheritance in JavaScript: Benefits of prototypal inheritance over classical?