3

As ES6 has arrived with class. So i want to know that when to use class and when to use simple function in javascript.

As function also capable to make new object.

user3852580
  • 51
  • 1
  • 4
  • You use `class` when you need a class (constructor function with prototype object). You use `function` when you need some other function. – Bergi May 27 '16 at 08:26

1 Answers1

8

Js Class is just syntactic sugar for

function SomeClass() {
    // this is basically a constructor
    this.property = 'some value';
};

SomeClass.prototype.someMethod = function() {
    // here you define method logic
}

If you use Babel or Typescript or you simply don't care for browser interoperabitility, you can use class notation, because its simpler to write, but in the essence, nothing changes.

As function also capable to make new object.

In JS everything but primitives (boolean, number) is created from Object so everytrhing even Array, String or {} or Function is capable of create new object, but not in the meaning of OOP languages like Java or C#.

You see, JS is prototypical language. Every object has special member called prototype. If you invoke someObject.someMember, the someMember is searched in someObject and if it isn't found there, the engine looks in someObject.protoype, where's typycally some previousObject. You could say, that someObject is subclass of previousObject, because it reference previousObject as its prototype. It's different from OOP languages, but it works almost the same way, as subclassing.

You can make new object from any object like this

var newObject = {};
newObject.prototype = previousObject;

or

var newObject = Object.create(previousObject);

or

function newObject () { ... }
newObject.prototype = previousObject;

or

class newObject extends previousObject { ... }
Rudolf Gröhling
  • 4,611
  • 4
  • 27
  • 37