JavaScript creating new instance of objects

user1991562 picture user1991562 · Mar 19, 2013 · Viewed 85.7k times · Source

So I am designing a grade book interface and I have a course defined as:

<script>
course = new Object();
 var name;
 var gradingareas;
 var finalgrade;
</script>

then later I want to create a new instance:

 var gradingareas = new Array("Homework", "Classwork", "Exams");

 course1 = new course("CS1500", gradingareas, 85);

I have also tried without the var in front to no avail. I get an "Uncaught TypeError: Object is not a function" I am very new to javascript so I don't even know if Im going about this the correct way. Any help is appreciated Thanks.

Answer

Quentin picture Quentin · Mar 19, 2013

Your existing code:

// Creates a new, empty object, as a global
course = new Object();
// Creates three new variables in the global scope.
var name;
var gradingareas;
var finalgrade;

There is no connection between the variables and the object.

It looks like you want something more like:

function Course(name, gradingareas, finalgrade) {
    this.name = name;
    this.gradingareas = gradingareas;
    this.finalgrade = finalgrade;
}

Then:

var course1 = new Course("CS1500", gradingareas, 85);

Note the use of a capital letter for naming the constructor function. This is a convention in the JS community.