2013-05-30 66 views
0

看一看這段JavaScript代碼:分配操作是否總是從右向左複製數據?

var myString = new String(); 
myString.myObject = "myObject..."; 

//works fine as it shows "myObject..." 
console.log("myString.myObject  :" + myString.myObject); 
//OK myObject is also a string so it should give length and it works fine 
console.log("myString.myObject.length :" + myString.myObject.length); 
//it should not give anything or undefined since nothing is given to myString 
console.log("myString     :" + myString); 
//myString is not yet defined so it should give undefined or 0.. 
console.log("myString.length   :" + myString.length); 

//lets make a simple assignment 
myString = myString.myObject; 
//it should just copy value of myObject to myString so there are two copies of string "myObject.." 

//lets log all the data all the data as i did above 

console.log("myString.myObject  :" + myString.myObject); 

//and this part is giving error 
//console.log("myString.myObject.length :" + myString.myObject.length); 

console.log("myString     :" + myString); 
console.log("myString.length   :" + myString.length); 

在上半年(賦值之前),它正在爲我所預期,但轉讓之後它給出了一個錯誤。

看來myString.myObject在分配後被刪除。是嗎?。

當我嘗試訪問myString.myObject時,控制檯出現紅色錯誤。分配刪除myString.myObject,還是發生在這裏?

回答

5

當你做到這一點

myString = myString.myObject; 

你與它的myObject屬性值替換整個myString值。由於它本身沒有myObject屬性,因此您在分配後沒有。

完成此作業後,myString的值爲"myObject..."

相關問題