2017-02-22 56 views
-4

我該如何解決這個問題才能打印this should show?我正在構建一個應用程序,我需要obj: myObj甚至obj: 'myObj'來引用它自己。對象在JavaScript中如何引用自身?

第1-3行僅用於顯示錯誤。

let myObj = { 
 
    text: 'this shouldn\'t show' 
 
}; 
 

 
myObj = { 
 
    text: 'this should show', 
 
    obj: myObj 
 
} 
 

 
function show(object) { 
 
    document.write(object.text); 
 
} 
 

 
show(myObj.obj);

+0

'myObj.obj = MyObj中;'? – Ryan

+0

您正在用一個新對象覆蓋'myObj',並引用舊對象。 'let myObj = {text:'this should show'}; myObj.obj = myObj;' – Thomas

回答

0

這有沒有關係指向本身就是一個對象,它是通過object.property = object完全可以實現的。這裏有兩個不同的對象,依次分配到相同的變量。在第obj: myObjmyObj(變量)仍然包含您創建的第一個對象創建第二個對象文字時的時間點。

如果你希望對象指向自身,只需添加一個屬性正確的值:

myObj = { 
    text: 'this should show' 
} 

myObj.obj = myObj; 
-1
let myObj = { 
    text: 'this shouldn\'t show' 
}; 

myObj = { 
    text: 'this should show', 
} 
myObj.obj = myObj; 

function show(object) { 
    console.log(object.text); 
} 

show(myObj.obj); 

這應該工作

0
  1. let myObj = {
  2. text:'this should not'show'
  3. };

上面的代碼片斷創建了一個帶有「text」屬性的myObj變量。

4. myObj = { 
5. text: 'this should show', 
6. obj: myObj 
7. } 

上述代碼重寫變量「MyObj中」用新的對象結構與被初始化爲在1-3的文本屬性intialized在代碼行中創建的對象「文本」屬性和「OBJ」屬性價值如果你改變了代碼

let myObj = { 
    text: 'this shouldn\'t show' 
}; 

//Override the objects text property 
myObj.text = 'this should show'; 
//create a property obj and make it refer to the same object. 
myObj.obj = myObj; 

function show(object) { 
    document.write(object.text); 
} 

show(myObj.obj); 

'這不應該\' 噸秀」

它應該工作