I'm trying to understand how to use javascript prototypes and inheritance in Google Apps Script but apparently I'm still missing something.
Here is the structure I'm working on.
function Father ( ) {
this.init.apply ( this, arguments );
}
Father.prototype ={
init: function ( ) {
var optns = arguments[0] || {};
this.job = optns.job || "unemployed";
this.cars = optns.cars || [];
}
}
function Son ( ) {
this.init.apply ( this, arguments );
}
Son.prototype = {
init : function ( ) {
Father.prototype.init.apply (this, arguments);
var optns = arguments[0] || {};
this.computers = optns.tablets || [];
}
}
Son differs from Father just for the property to own computers.
function life() {
var Tom = new Father({job:'carpenter', cars: ['fiat']});
var Jim = new Son(Tom);
Jim.computers.push('iMac');
Jim.job = 'trader';
Jim.cars.push('bmw');
return
}
Here I want the Son instance Jim to start with the same values as Tom (being a carpenter and owning a fiat) but then, as life goes on, I'm expecting Jim's values to change independently from Tom. In fact, I can add a computer and change job to Jim without affecting Tom but when I add a car to Jim, 'bmw' is also added to Tom's cars. Why???
Note: the code works fine if I replace this line
var Jim = new Son(Tom);
with
var Jim = new Son({job:'carpenter', cars: ['fiat']})
but I don't get why.