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,还是这里发生了其他事情?

4

1 回答 1

5

当你这样做时

myString = myString.myObject;

myString您正在用其myObject属性值替换整个值。由于它本身没有myObject属性,因此您myString在分配后没有属性。

在此分配之后, 的myString值为"myObject..."

于 2013-05-30T18:36:16.783 回答