lab11: impl
This commit is contained in:
59
lab11/student.js
Normal file
59
lab11/student.js
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
Create a 'Student' constructor, like we did for Cat in class.
|
||||
It should have the following fields:
|
||||
*firstName
|
||||
*lastName
|
||||
*studentID
|
||||
*display -- A function that prints out the firstName, lastName, and studentID number.
|
||||
To invoke it, you should call `student.display()`.
|
||||
|
||||
Create an array of new students.
|
||||
Add a 'graduated' property to just one of your students.
|
||||
|
||||
Now create another student **without** using the constructor.
|
||||
(In other words, use the object literal `{}` syntax).
|
||||
Set the prototype chain manually using the __proto__ field.
|
||||
Make sure the display method still works (without you having to add it to the object explicitly).
|
||||
*/
|
||||
|
||||
// Create a Student constructor
|
||||
function Student(firstName, lastName, studentID) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.studentID = studentID;
|
||||
}
|
||||
|
||||
// Add the display method to the prototype
|
||||
// Manual student doesn't work if display is defined in the constructor
|
||||
Student.prototype.display = function () {
|
||||
console.log(`${this.firstName} ${this.lastName}, ID: ${this.studentID}`);
|
||||
};
|
||||
|
||||
var students = [
|
||||
new Student("John", "Smith", "12345"),
|
||||
new Student("Jane", "Doe", "67890"),
|
||||
new Student("Alice", "Johnson", "11111"),
|
||||
];
|
||||
|
||||
// Add a 'graduated' property to just one of the students
|
||||
students[0].graduated = true;
|
||||
|
||||
// Student without using the constructor (object literal syntax)
|
||||
var manualStudent = {
|
||||
firstName: "Bob",
|
||||
lastName: "Wilson",
|
||||
studentID: "99999",
|
||||
__proto__: Student.prototype,
|
||||
};
|
||||
|
||||
// Test
|
||||
console.log("Students created with constructor:");
|
||||
students.forEach(function (student) {
|
||||
student.display();
|
||||
if (student.graduated) {
|
||||
console.log("This student has graduated!");
|
||||
}
|
||||
});
|
||||
|
||||
console.log("\nManual student with prototype:");
|
||||
manualStudent.display();
|
||||
Reference in New Issue
Block a user