부모 객체 내에서 하위 객체의 값을 변경하는 데 Javascript가 어떻게 반응하는지 알아보기 위해 작은 테스트를 수행했습니다. 부모가 자식을 참조하고 새로운 값으로 최신 정보를 유지하는지, 인스턴스화 된 자식의 초기 상태 만 유지 하는지를보고 싶었습니다.Javascript 객체 참조 자식
난 당신이 콘솔에서 볼, 작은 모듈을 coords.js
var NS = NS || {}; NS.Coords = function(){ var __parentArray = {}; var __childArray = {}; addToParent = function(){ __childArray['value'] = "Initial"; __parentArray['child'] = __childArray; }, showParent = function(){ console.log("Parent: ",__parentArray); console.log("Child within parent: ",__parentArray['child']); }, changeChild = function(){ __childArray['value'] = "Changed"; }, showChild = function(){ console.log("Child: ",__childArray]); }; return { addToParent: addToParent, showParent: showParent, changeChild: changeChild, showChild: showChild }; }();
그리고 main.js
이를 실행하면
var NS = NS || {};
// @codekit-prepend "Coords.js"
console.log("=============================");
console.log("Startpoint point");
console.log("=============================");
var coords = NS.Coords;
coords.addToParent();
coords.showChild();
coords.showParent();
console.log("=============================");
console.log("Changed child value");
console.log("=============================");
coords.changeChild();
coords.showChild();
coords.showParent();
에서
을 직접 보여 때, 아이는 예상 된 "초기"값과 "변경된"값을 보여줍니다.
그러나 부모는 항상 참조하는 하위 개체의 "변경된"값을 표시합니다. changeChild()가 호출되기 전에도. 이유는 모르겠다. 값을 변경하지 않고도 변경되었음을 알 수 있습니다. 슈퍼 간단한 것을 놓친 건가요? 아니면 여기서 무슨 일이 일어나고 있는지 오해하고 있습니까?
항상 (항상 그런 것은 아니지만 바이올린을 가지고있는 것이 좋습니다) 바이올린을 설정해야하므로 결과를 확인할 수도 있습니다. –
나는 n00b이다. 할거야! – Gurnzbot