Object vs Class vs Function
class, javascript, oop
Solution
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 at first believe 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?
Problem
I was wondering - what's the difference between JavaScript objects, classes and functions? Am I right in thinking that classes and functions are types of objects? And what distinguishes a class from a function? Or are they really the same thing, just the term for them changes according to how they are used? ``` function func() { alert('foo'); } // a function func(); // call the function - alerts 'foo' var func2 = function () { alert('hello'); } // acts the same way as 'func' surely? func2(); // alerts 'hello' var Class = function() { alert('bar'); }; // a class var c = new Class(); // an istance of a class - alerts 'bar' ``` Sure, classes have methods and properties and can be instantiated - but then, I could do the same with any old function - or not?