Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  195] [ 6]  / answers: 1 / hits: 146476  / 11 Years ago, mon, july 8, 2013, 12:00:00

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?


More From » class

 Answers
54

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?


[#77135] Saturday, July 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madilynndiannac

Total Points: 191
Total Questions: 93
Total Answers: 111

Location: France
Member since Thu, Oct 15, 2020
4 Years ago
madilynndiannac questions
Sat, Aug 22, 20, 00:00, 4 Years ago
Tue, Jul 28, 20, 00:00, 4 Years ago
Thu, Jul 9, 20, 00:00, 4 Years ago
Mon, Jun 1, 20, 00:00, 4 Years ago
Mon, Jan 13, 20, 00:00, 4 Years ago
;