Ok, so I discovered a whole bunch of things wrong with my code above!.
Let me list the things that are wrong so that I may better understand JavaScript.
[1] The way I have defined the function printCarDetails() inside the constructor function Car,
function printCarDetails() {
console.log("make = " + make + ", model = "+ model + ", age = " + age);
does not create a “printCarDetails” property on Car or any new object created by it. It creates a private function (aka method) in Car. Being private, this function is not accessible outside Car. (Private methods are inner functions of the constructor. Also, private methods cannot be called by public methods. Public methods are those that are defined on the prototype of the function) (http://javascript.crockford.com/private.html)
It gives me the following error when I execute “myCar.printCarDetails();”
TypeError: myCar.printCarDetails is not a function
To make “printCarDetails” a property of any object created from Car I need to use -
this.printCarDetails = function() {
console.log("make = " + make + ", model = "+ model + ", age = " + age);
};
Now when I execute “myCar.printCarDetails();”,
it displays “make = Nissan, model = Sentra, age = 1988”
[2] As @kevcomedia correctly pointed out:
Car.printCarDetails = function() {
console.log("This function has changed");
}
This has no effect on any object created by using new Car(…). Rather. this defines a new property for Car as an object.
[3] The constructor function, when called using new, creates “deep” clones/copies of Objects and Arrays and Functions for the newly created objects.
For example,
If we then define 2 objects as such:
var myCar = new Car(“Nissan”, “Sentra”, “1988”);
var otherCar = new Car(“Toyota”, “Camry”, “1993”);
on running the following tests, we get these results:
(a) console.log(myCar.internalCarObject === otherCar.internalCarObject); (False)
(b) console.log(myCar.printCarDetails === otherCar.printCarDetails); (False)
(c) console.log(myCar.internalArray === otherCar.internalArray); (False)
(d) console.log(myCar.internalCarObject);
{ make: 'Nissan',
model: 'Sentra',
age: '1988',
internalinternalObject: { name: 'value' } }
[4] This is why, as @laney stated, [quote=“laney, post:3, topic:23705”]
Car.prototype.printCarDetails = …
[/quote]
it is better to use the “prototype” property of Car and declare functions in it. This way, objects created from the Constructor Function don’t have their own instances of the Function (which uses up extra memory unnecessarily). All instances of Car can now share the same function.