Create Javascript Object : new Notation and Constructor Functions
• constructor function will be used as the blueprint when creating new instances with the new kw
• Constructor function special b/c you can refer to an instance by using the this keyword.
• Convention to use uppercase at the beginning of a constructor function -- e.g., Car.
• Ea instance has speed and type properites and a function called drive.
• this keyword used to create the instance properties for each instance, each car.
• Ea instance of car will have its own instance of drive function.
• For creating "static" functions -- a function that is singular, persists, can be used by all objects-- use prototype.
function Car(type) {
this.speed = 0;
this.type = type || "No type";
this.drive = function(newSpeed) {
this.speed = newSpeed;
}
}
//creating a new instance of the Car object, the bmw.
var bmw =new Car("BMW");
console.log(bmw.speed); // outputs 0
console.log(bmw.type); // outputs "BMW"
bmw.drive(80);
console.log(bmw.speed); // outputs 80