Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/Why Use Class in JavaScript Over a Constructor? [duplicate]

Yes there are many ways to create and use objects. So why/when is it better to create a constructor versus declare a class and use the constructor() method? My instructor said it doesn't make a difference but I don't believe him.

// 1
function Grumpy(name, profile, power){
    this.name = name;
    this.profile = profile;
    this.power = power;
}

Versus

// 2
class Grumpy{
    constructor(name, profile, power){
        this.name = name;
        this.profile = profile;
        this.power = power;
    }
}
like image 793
Katherine R Avatar asked Dec 14 '17 12:12

Katherine R


People also ask

Why you should use classes in JavaScript?

JavaScript still follows a prototype-based inheritance model. Classes in JavaScript are syntactic sugar over the prototype-based inheritance model which we use to implement OOP concepts. Thus the introduction of classes in JS made it easier for developers to build software around OOP concepts.

What is the difference between constructor and class in JavaScript?

A class is a constructor technically. Any object with a [[ Construct ]] internal method is considered one. All constructors are functions, but not all functions are constructors. Functions in Javascript can be of many kinds.

Why do we use constructor in JavaScript class?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

Can a JavaScript class have two constructors?

Definition and Usage Note: A class cannot have more than one constructor() method. This will throw a SyntaxError .


1 Answers

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

For more defailts, see MDN

like image 144
zabusa Avatar answered Nov 14 '22 21:11

zabusa