Information



Tags



Share

How to use JavaScript Classes with Objects

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition(1)

Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError.

Code

Using classes is an easy way to collect functions pertaining to a special task such as Accounting or Calculating classes so that you do not have to either recall or re-write your functions including objects while coding a new page.

To create a new object in a class, you should comprehend the constructor method which is a special method for classes. And, do not forget that a SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

Nevertheless, you can create special functions other than the constructor method by implementing a Static method, which is well-explained on the code.

As an example, I choose to show how to create a rudimentary accounting class for each person to be saved in a database.


// Create Accounting Class.

class Accounting {
// Define an object with the constructor method.
constructor(firstName, lastName, saveId, country, Net_Income, Break_Even_Point) {
this.firstName = firstName;
this.lastName = lastName;
this.id = function(){
return "Name: " + firstName + " " + lastName + "<br> Line: " + saveId + "<br> Country: " + country;
};
this.table = function(){
return "Net Income: " + Net_Income + "<br> Break-Even Point: " + Break_Even_Point;
};
}

// Use these special functions even outside the class itself.
static NetIncome(Revenues, Expenses){
return Revenues - Expenses;
}

static BreakEvenPoint(FixedCosts, SalesPrice, VariableCostPerUnit){
return FixedCosts / (SalesPrice - VariableCostPerUnit);
}

}

// Define a new entry.
var person = new Accounting("Jane", "Doe", 1152, "USA", Accounting.NetIncome(1000, 850), Accounting.BreakEvenPoint(100, 80, 40));

// Show results.
document.getElementById("id").innerHTML = person.id();

document.getElementById("table").innerHTML = person.table();

Result:

article-image
Figure - 41.1

References

(1) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes