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.
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 { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With