flexible constructor in JavaScript

Javascript provides flexible constructor. Below are sample code that implement the flexible constructor:

var Student = function(_department, _course, _year){
	department = _department || "";
	course = _course || "";
	year = _year || "";

	this.set_department = function(_department){
		department = _department;
	}

	this.set_course = function(_course){
		course = _course;
	}

	this.set_year = function(_year){
		year = _year;
	}

	this.display_information = function(){
		console.log("Information of the student:");
		console.log("Department: " + department);
		console.log("Course: " + course);
		console.log("Year: " + year);
	}
}

//constructor
var obj_student = new Student("Computer Information Scince", "ICT", "2");
obj_student.display_information();

var another_obj_student = new Student();
another_obj_student.set_department("Technology");
another_obj_student.set_course("BIS");
another_obj_student.set_year("Foundation");
another_obj_student.display_information();

Sample output:

Information of the student:
Department: Computer Information Scince
Course: ICT
Year: 2
Information of the student:
Department: Technology
Course: BIS
Year: Foundation
Leave a comment

0 Comments.

Leave a Reply

( Ctrl + Enter )