Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: What is the difference between Function and Class

With the release of ECMAScript 6 on June 2015, Javascript classes syntax was introduced.

This syntax:

class Polygon {
      constructor(width, height) {
        this.width = width;
        this.height = height;
      }
}

is basically same as:

function Polygon(width, height) {
    this.width = width;
    this.height = height;
}

So what is the benefit of using class instead of traditional function? And in what condition I should use class instead of function?

like image 606
Edward Anthony Avatar asked Mar 19 '16 08:03

Edward Anthony


People also ask

What is the difference between function and class?

Functions do specific things, classes are specific things. Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

Are classes in JavaScript just functions?

That's because JavaScript doesn't have a concept of methods. Functions are first-class in JavaScript, and they can have properties or be properties of other objects. A class constructor creates an instance of the class. A constructor in JavaScript is just a plain old function that returns an object.

What is the difference between function and object in JavaScript?

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. For more examples and explanations, see the JavaScript guide about functions.

What is difference between function and method in JavaScript?

In short: a method is a function that belongs to a class. In JavaScript, however, a method is a function that belongs to an object. Everything in JavaScript is an object; a function is an object; an Array is an object.


1 Answers

There are some differences between Class and Function - most people will start by saying that the Class is "just syntax sugar", but that sugar does matter quite a bit. When the JS parser is processing the JavaScript code the parser will save them in different AST nodes, like shown here the ClassDeclaration and ClassExpression are different node types in the resulting AST tree:

https://github.com/estree/estree/blob/master/es2015.md#classes

You can see that for this parser, the new ES6 Classes spec introduces a number of new AST elements to the syntax:

  • ClassBody
  • MethodDefinition
  • ClassDeclaration
  • ClassExpression
  • MetaProperty

Since the AST syntax is not standard, there can be more or less types depending on the parser, but what is important to notice that when the code enters the class declaration or class expression it will be interpreted differently by the JavaScript engine.

This means, that Class and Function declarations can not be exchanged. You can see this if you try to write

class notWorking {
  return 1;  // <-- creates a parser error
};

This is because when the parser encounters the class -keyword, it will start treating the following code as ClassBody of either ClassDeclaration or ClassExpression and then it expects to find MethodDefinitions.

This is a small problem, because creating private variables becomes a bit more challenging. The function declaration could define a private variable neatly like this:

function myClass() {
    var privateVar;
}

The class declaration can not have this:

class myClass {
    var privateVar; // ERROR: should be a method
}

This is because the syntax of class allows only methods to be declared inside the class body. At least right now.

However, there exists a proposal for creating private fields:

https://github.com/zenparsing/es-private-fields

Thus, in the future you might be able to say

class myClass {
   #privateVar; // maybe this works in the future?
}

There is a separate answer considering the private properties in ES6 Classes, which is suggesting some workarounds, like the use of Symbols:

Private properties in JavaScript ES6 classes

var property = Symbol(); // private property workaround example
class Something {
    constructor(){
        this[property] = "test";
    }
}

Naturally there are more differences between classes and functions. One of them is Hoisting 1 - unlike Functions, you can't declare the Class anywhere in the scope:

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it

The Class declarations and Function declarations are quite similar;

function foo1() {} // can be used before declaration
class  foo2{}      // new foo2(); works only after this declaration

The class expressions work quite similarly to function expressions, for example they can be assigned to a variable:

var myClass = class foobar {};

More differences are 1

  1. The Class expression / declaration body is always executed in Strict mode - no need to specify that manually
  2. Classes have special keyword constructor - there can be only one of them, or error is thrown. Functions could have multiple definitions of variable of function named "constructor"
  3. Classes have special keyword super which relates to the parent classes constructor. If you are inside the constructor you can call super(x, y); to call the parent class constructor but inside the Method you can call super.foobar() to create call to any parent class function. This kind of functionality is not available for standard Functions although you might emulate it with some custom hacking.
  4. Inside class body you can define function with static keyword so it can be called using only ClassName.FunctionName() -syntax.
  5. Both class declarations and expressions can use extends keyword like class Dog extends Animal
  6. MethodDeclaration does not need function -prefix, thus you can define function "ok" inside the class "m" like this: class m { ok() { } }. Actually it is not even allowed to define function as class m { function ok() { } }

However, after the parser has completed it's job, the class instance is essentially running the same way as any other object.

The new ES6 Class syntax is essentially more clear way of expressing objects in a traditional OOP way and if you like it, then you should use it.

EDIT: also, the ES6 Class syntax has also another limitation: it does not allow the member functions to use lexically binded using fat arrow. ES7 seems to have experimental feature allowing it. That can be useful for example when binding methods to event handlers, the related question is here.

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

like image 62
Tero Tolonen Avatar answered Oct 11 '22 11:10

Tero Tolonen