Reputation: 414
Background: C# developer recently diving into javascript
Below are two ways of creating objects in JavaScript. What's the difference between them, which method should I use/prioritize when creating objects and why?
class John {
constructor(name, birth, height) {
this.name = name;
this.birth = birth;
this.height = height;} }
var Person = function(name, birth, height) {
this.name = name;
this.birth = birth;
this.height = height;}
Upvotes: 3
Views: 2744
Reputation: 4098
The class
syntax is code from a newer "version" of JavaScript referenced as ES6.
While the function
declaration was used before and is referenced as "prototypes".
So to answer your question what to prioritize, it really depends on what browsers you want to support. You can check browser support using caniuse: https://caniuse.com/#search=es6%20classes
Coming from C# I think the biggest difference for you will be the browser support thingy. As you don’t know where your code will be run really, you should check caniuse quite often.
As others mentioned there are some compilers that will take that pain away from you as for example bublé or babel. However, note that they come with their own advantages/disadvantages. Here is the first tutorial I found on the topic: https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them
That being said, welcome to the JavaScript community.
Upvotes: 0
Reputation: 1021
Before es6, constructor functions were how we could implemented class structures and oop. You still can, but as a c# developer you will be more accustomed to class notation. As long as the browser supports es6. They are both functions
Upvotes: 0
Reputation: 1074148
They do largely the same thing. class
syntax was introduced in ES2015, and does a few things for you:
It builds in a check that the function was called as part of creating a new object, eliminating a whole class of errors that calling a constructor without new
allows.
It enables the use of super
in constructors and methods.
It's simpler, particularly if you do subclasses.
It's much simpler if you do subclasses of built-ins like Error
or Array
(you can do it without class
).
But you can do all of that without class
if you prefer to use the older syntax.
Of course, you can't use the new syntax on outdated browsers like IE without transpiling to the older syntax via tools like Babel.
(And obligatory note: Using class-like trappings on JavaScript's prototypical inheritance is a style choice, not a requirement. If you prefer, you can just use prototypical inheritance directly.)
You may also find this answer useful, comparing class
syntax with doing the same thing with function
syntax.
Upvotes: 9