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.
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.
Answer. To create a new instance of an object, we use the "new" keyword. This keyword creates a new instance of an object, which we can then assign to a variable, or invoke methods. For example, to create a new StringBuffer object, we would use the new keyword in the following way.
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.
JS is prototypical, rather than class based and if you are new to it there are advantages to learning this immediately rather than trying to mush classical inheritance models from it, however, classical inheritance is alive and well in JS.
Anyhow, to answer how you would access your variables:
course1.name
works fine with the example above.
If you wanted to privatise your data you could take this approach using closure:
var Course = function(name, grade) { // Private data var private = { name: name, grade: grade } // Expose public API return { get: function( prop ) { if ( private.hasOwnProperty( prop ) ) { return private[ prop ]; } } } };
Then instantiate a new object:
var course = new Course('Programming with JavaScript', 'A');
and start using all that private data:
course.get('name');
Of course, you'd probably want setters to manipulate that data too ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With