Menu Search Me

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; = science;

//Define the object "student"

function student(name,age, grade) { = 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 "" english grade is "+bobGrade.english);

Objects with Properties & Methods

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

   function displayProfile() {
    document.write("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: " + + "<BR>");

  function student(name,age, grade) { = 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