Menu Search Sign up

JavaScript Objects

There are 2 types of JavaScript objects: objects with properties, and objects with properties AND functions.

In JavaScript, you first define the object (what properties does it have, and what functions does it have), then you instantiate the object by assigning values to the object; then you use the object by calling its functions, referencing its property values, or modifying its property values.

Objects with Properties

//Define the object "grade"

function grade (math, english, science) {
    this.math = math;
    this.english = english;
    this.science = science;
  }

//Define the object "student"

function student(name,age, grade) {
    this.name = name;
    this.age = age;
    this.grade = grade;
  }

//Instantiate 2 grade objects

  var bobGrade = new grade(75,80,77);
  var janeGrade = new grade(82,88,75);

//Instantiate 2 student objects

  var student1 = new student("Bob",10,bobGrade);
  var student2 = new student("Jane",9,janeGrade);

//Use the grade and student objects

  alert("Student1 "+student1.name+" english grade is "+bobGrade.english);

Objects with Properties & Methods

//Declare the object student with a method of displayProfile()

   function displayProfile() {
    document.write("Name: " + this.name + "<BR>");
    document.write("Age: " + this.age + "<BR>");
    document.write("Mother's Name: " + this.mother + "<BR>");
    document.write("Math Grade: " + this.grade.math + "<BR>");
    document.write("English Grade: " + this.grade.english + "<BR>");
    document.write("Science Grade: " + this.grade.science + "<BR>");
  }

  function student(name,age, grade) {
    this.name = name;
    this.age = age;
    this.grade = grade;
    this.mother = mother;
    this.displayProfile = displayProfile;
  }

//Instantiate the student object

  var student1 = new student("Bob",10,77);

//Use the student1 object by calling its displayProfile() method

  student1.displayProfile();