Object vs Class vs Function

JavascriptClassOop

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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](http://aaditmshah.github.io/why-prototypal-inheritance-matters/#constructors_vs_prototypes "Aadit M Shah | Why Prototypal Inheritance Matters").

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: https://stackoverflow.com/q/2800964/783743

Solution 2 - Javascript

Update 2015

There are classes in JavaScript they just aren't used on older browsers:

Compatibility screenshot

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

It has constructors, extensions, and the like.

class Cat { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Lion extends Cat {
  speak() {
    super.speak();
    console.log(this.name + ' roars.');
  }
}

Solution 3 - Javascript

A Class in JS:

function Animal(){  

    // Private property
	var alive=true;

    // Private method
	function fight(){ //... }   

    // Public method which can access private variables
	this.isAlive = function() { return alive; } 

    // Public property
    this.name = "Joe";
}

// Public method
Animal.prototype.play = function() { alert("Bow wow!"); }

// .. and so on

Now when you create it's object

var obj = new Animal();

You can expect anything of this object as you would from objects in other language. Just the efforts to achieve it, was a bit different. You should also be looking at inheritance in JS.


Getting back too your question, I'll reword it as:

Class  : A representation of a set with common properties.
object : One from the set with the same properties.


var Class = function() {alert('bar');}; // A set of function which alert 'bar'
var object = new Class();               // One of the functions who alert's 'bar'.

Solution 4 - Javascript

JavaScript does not have classes, and functions are actually objects in JavaScript (first-class citizens). The only difference that function objects have is that they are callable.

function func() { alert('foo'); } // a function - Correct

func(); // call the function - alerts 'foo' - Correct

var func2 = function () { alert('foo'); } // same as 'func' surely? - Nope, func2 is a different object, that apparently does the same thing when called.

var Class = function() { alert('bar'); }; - It's a function with no name stored in variable Class.

var c = new Class(); - Calls function stored in Class supplying new empty object as this and returning that object. Functions called as new functionA() are expected to work as constructors and prepare a newly created object (this). In your case - constructor does nothing with the object and just alerts bar.

Solution 5 - Javascript

You also get classes in ES6 that look like this:

//class
class Cat {
    //constructor
    constructor() {
        this.name = 'Snowball';
    }

    //method
    meow() {
        console.log('Hello, nyah! My name is ' + this.name + ' nyah!~');
    }
};

Solution 6 - Javascript

There are no classes in javascript. But, there are ways to make a function to behave like a class in other languages.

A very good explanation is given here 3 way to define a class in js

Also, found a very good reference for OOP in Javascript

Solution 7 - Javascript

Object is the base type in JavaScript i.e. all the user defined data types inherits from Object in one way or another. So if you define a function or a class [note as of now JS doesn't support class construct, but its proposed in ECMAScript version 6], it will implicitly inherit from Object type.

Classes are really used for encapsulating logical functions and properties into one type / entity and you can 'new' it up using constructor syntax. So if you define a 'Customer' class, you can instantiate it multiple times and each instance / object can have different values. They can even share the values if you define class level value using prototype.

Since JS doesn't support class construct at the moment, functions can really act as individual method as well as container for other functions or types.

I hope with ECMAScript 6 we will have clear separation between these constructs similar to what we have in other languages like C#, Java etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSean BoneView Question on Stackoverflow
Solution 1 - JavascriptAadit M ShahView Answer on Stackoverflow
Solution 2 - JavascriptRogerView Answer on Stackoverflow
Solution 3 - JavascriptloxxyView Answer on Stackoverflow
Solution 4 - JavascriptmishikView Answer on Stackoverflow
Solution 5 - JavascriptShanaSkydancerView Answer on Stackoverflow
Solution 6 - JavascriptTalaView Answer on Stackoverflow
Solution 7 - JavascriptPrasad HonraoView Answer on Stackoverflow