JavaScript – Classes and Objects

Class:

  • Class – is a collection of variables and methods
  • Variables – Store information
  • Methods – Process information

Object:

  • Real world entity (Human, House, Car, Laptop, Mobile….)
  • Object – memory allocation of class.

Banking Application: Account class – Number of Account Holders (objects)

Constructor():

  • We create object to class using “new” operator
  • “new” operator allocates memory to variables.
  • To provide initial values to variables we use constructor.
  • “this” is used to point an object.

Create Object and Print details:

<!doctype html>
<html>
	<body>
		<script>
			class Account{
				constructor(num, name, balance){
					this.num = num;
					this.name = name;
					this.balance = balance;
				}
			}
			var e = new Account(101, "Amar", 5000);
			document.write("Num : " + e.num + "<br/>");
			document.write("Name : " + e.name + "<br/>");
			document.write("Balance : " + e.balance + "<br/>");
		</script>
	</body>
</html>

Create multiple objects and print details using method:

<!doctype html>
<html>
	<body>
		<script>
			class Account{
				constructor(num, name, balance){
					this.num = num;
					this.name = name;
					this.balance = balance;
				}
				details(){
					document.write("Num : " + this.num + "<br/>");
					document.write("Name : " + this.name + "<br/>");
					document.write("Balance : " + this.balance + "<br/>");
				}
			}
			var e1 = new Account(101, "Amar", 5000);
			var e2 = new Account(102, "Harin", 7000);
			var e3 = new Account(103, "Annie", 9000);
			e1.details();
			e2.details();
			e3.details();
		</script>
	</body>
</html>
Scroll to Top