Search⌘ K

More on Objects: this Keyword

Explore how to use the this keyword in JavaScript to create object constructors and methods, enabling you to manage individual object properties effectively. Understand how to build objects using functions and instantiate them with the new keyword, preparing you for more advanced concepts like DOM manipulation.

Let’s go back to the student example we were using in earlier lessons.

Node.js
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:

Node.js
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:

Node.js
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. Make sure ...