最近,我一直在使用JavaScript進行更多工作,我不明白爲什麼會發生以下情況。我沒有提供數百行代碼,而是創建了重現問題的場景。JavaScript - 將多個變量設置爲對象屬性不會改變基礎值
問題:
設置多個變量的一個對象的屬性不會改變對象的潛在價值。
實施例:
在以下示例中,我已經創建了兩個類:
//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
};
}
現在,我執行以下操作:
- 創建一個新的公司,並在構造函數中添加新的子公司:
- 定義與/子公司性質
//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
下面的代碼是其他變量問題所在:
當我嘗試更改變量類型時,公司內部值不變...
//does not work
type =
type === 'small' ?
'large' :
'small';
然而,如果我使用信息並引用屬性類型(info.type
),該值的變化...
//works
info.type2 =
info.type2 === 'small' ?
'large' :
'small';
我假定由於每個可變從另一個導出,類型將相當於company.subsidiary[0].information.type
,但似乎並非如此。
我錯過了什麼嗎?
任何援助將不勝感激。謝謝!
謝謝您花時間回答!但我仍然有點困惑。變量'info'不會是'company.subsidiary [0] .information'的副本嗎?爲什麼要改變'info.type'改變公司內的價值? – Dom
因爲你明確地**更新了對象屬性的值。我會補充一點答案。 – Pointy
非常感謝您花時間解釋這一點!你在解釋究竟發生了什麼時做了一件了不起的工作!再次感謝,我會盡快接受你的回答。 – Dom