Simple Composition Demonstration in JavaScript [Beginners Guide]




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function Course(courseCode, courseTitle) {
    this.courseCode = courseCode;
    this.courseTitle = courseTitle;
}

function PhoneNumber(countryCode, cityCode, lineNumber) {
    this.countryCode = countryCode;
    this.cityCode = cityCode;
    this.lineNumber = lineNumber;
}

function Address(streetAddress, town, city, country, phoneNumber) {
    this.streetAddress = streetAddress;
    this.town = town;
    this.city = city;
    this.country = country;
    this.phoneNumber = phoneNumber;
}

function Student(name, email, cnic, course1, course2, address) {
    this.name = name;
    this.email = email;
    this.cnic = cnic;
    this.course1 = course1;
    this.course2 = course2;
    this.address = address;
    this.getJSON = function () {
        return this;
    };
    this.information = function () {
        console.log('Name: ', this.name);
        console.log('Email: ', this.email);
        console.log('CNIC: ', this.cnic);
        console.log('Course 1: ');
        console.log('      Code: ', this.course1.courseCode);
        console.log('     Title: ', this.course1.courseTitle);
        console.log('Course 2: ');
        console.log('      Code: ', this.course2.courseCode);
        console.log('     Title: ', this.course2.courseTitle);
        console.log('Address: ');
        console.log('    Street: ', this.address.streetAddress);
        console.log('      Town: ', this.address.town);
        console.log('      City: ', this.address.city);
        console.log('   Country: ', this.address.country);
        console.log('   PhoneNo: ');
        console.log('   Country# ', this.address.phoneNumber.countryCode);
        console.log('      City# ', this.address.phoneNumber.cityCode);
        console.log('      Line# ', this.address.phoneNumber.lineNumber);
    };
}

var name = "Jhon",
    email = "jhon@gmail.com",
    cnic = "111-222-333",
    course1 = new Course('CS401', 'Web Development'),
    course2 = new Course('CS402', 'Machine Learning'),
    phoneNumber = new PhoneNumber(1, 718, 1112223),
    address = new Address('House# 1', 'Albion', 'New York', 'USA', phoneNumber);

var student = new Student(name, email, cnic, course1, course2, address);

console.log(student.getJSON());

No comments