Recently, I have been working more with JavaScript and I cannot understand why the following happens. Rather than providing hundreds of lines of code, I have created a scenario that recreates the problem.
Issue:
Setting multiple variables to an object's properties does not change the object's underlying value.
Example:
In the following example, I have created two classes:
//company
function Company(name, subsidiary) {
var self = this;
self.name = name;
self.subsidiary = subsidiary;
};
//subsidiary
function Subsidiary(name, type) {
var self = this;
self.information = {
name: name,
type: type,
type2: type
};
}
Now, I do the following:
- create a new company and add new subsidiary in the constructor:
- define other variables related to the company/subsidiary properties
//new company
var company = new Company(
'Company 1', [
new Subsidiary('Subsidiary 1', 'small')
]),
subsid = company.subsidiary[0], //get first subsidiary
info = subsid.information, //get information
type = info.type; //get type
The following code is where the problem lies:
When I try to change the variable type, the value within company does not change...
//does not work
type =
type === 'small' ?
'large' :
'small';
However, if I were to use info and reference the property type (info.type), the value changes...
//works
info.type2 =
info.type2 === 'small' ?
'large' :
'small';
I assumed since each variable derives from another, type would be equivalent to company.subsidiary[0].information.type, but that does not seem to be the case.
Am I missing something?
Any assistance would be greatly appreciated. Thank you!