More on Objects: this Keyword
Get an understanding of how object-oriented programming is useful for object constructors and the "this" keyword for creating reusable templates with properties and methods.
We'll cover the following...
Let’s go back to the student
example we were using in earlier lessons.
Press + to interact
var student = {name: "Mary",age: 10};
In this example, each student has a name
and an age
property. If we wanted to create another student, we could define another object with the same properties:
Press + to interact
var student2 = {name: "Michael",age: 12};
However, if we had to define many student objects, having to write out the same properties over and over again will get tiring. A better way to create a student
object would be to create a function that returns an object:
Press + to interact
var createStudent = function(name, age) {var student = {name: name,age: age}return student;}var student1 = createStudent("Mary", 10);var student2 = createStudent("Michael", 12);console.log("Students:", student1.name, student2.name);
Exercise #
Use the createStudent
function to create a new student, stored in a variable named student3
...