I've been doing some research into OOP in JavaScript and I came across these notes on MDN.
Function syntax
I have created a few classes before, but the syntax I have used has been creating a function. See below.
function myFunction(myProp1, myProp2)
{
// see if set, otherwise use the default value (after the colon)
myProp1 = typeof myProp1 !== "undefined" ? myProp1 : 1;
myProp2 = typeof myProp2 !== "undefined" ? myProp2 : 2;
// simple function
this.doSomething = function ()
{
return myProp1 + myProp2;
}
}
var myObj = new myFunction(2, 4);
myObj.doSomething(); // returns 6
Class syntax
Today I found out that it is possible to achieve the same using the following code.
class myClass
{
constructor(myProp1, myProp2)
{
// see if set, otherwise use the default value (after the colon)
this.myProp1 = typeof myProp1 !== "undefined" ? myProp1 : 1;
this.myProp2 = typeof myProp2 !== "undefined" ? myProp2 : 2;
}
// simple function
doSomething()
{
return this.myProp1 + this.myProp2;
}
}
var myObj = new myClass(2, 4);
myObj.doSomething(); // returns 6
Now lies the question
Is there truly a difference or is it simply a difference in taste as to which method I use to create new objects?
Edit
For clarification, I will put some queries below.
Questions:
- @MasterBob mentioned about support. Is the
class
way not supported in all browsers? If not, then which browsers aren't supported? - Inheritance. Do either version inherit different properties or are they completely identical?