The most common approach to achieving this is by defining a JavaScript function where we then create an object using the new
keyword. this
can be used to help define new properties and methods for the object as follows:
1 2 3 4 5 6 7 8 9 10 11 12 | // A car "class" function Car( model ) { this .model = model; this .color = "silver" ; this .year = "2012" ; this .getInfo = function () { return this .model + " " + this .year; }; } |
We can then instantiate the object using the Car constructor we defined above like this: