标签:
看到一个小例子讲了JS的引用指针内容,记录一下:
var a = {n:1}; var b = a; a.x = a = {n:2}; console.log(a.x); //undefined console.log(b.x); //[object Object]
分析:
var a = {n:1}; //a指向对象{n:1} var b = a; //a与b都指向{n:1}
a.x = a = {n:2}; //JS中运算顺序从右到左;点运算符的优先级最高;因此这里先进行a.x运算:给a所指向的{n:1}对象添加了一个x属性,值为undefined。
//然后进行a={n:2}的计算: 这里将a指向了一个新创建的{n:2}的对象
//最后进行的是a.x = a的计算 , 在这里因为a.x已经进过了运算,已经解析了这个x属性是属于对象{n:1}的,在这里就不再进行解析;
//那么这里就将a所指的{n:2}对象赋给了{n:1}中的x属性指针,让这里的x指向{n:2}对象
console.log(a.x); //undefined {n:2}对象中没有x属性,向上寻找也没有找到于是输出undefined console.log(b.x); //[object Object] 这里是{n:1}里的x属性,因为其指向的是b。 这里的[object Object]是因为输出对象的字符串形式,是隐式调用了Object对象的
//toString()方法。其形式是“[object Object]”,所以这里表示的只是一个对象。
附:Object.prototype.toString方法:
var arr = []; console.log(Object.prototype.toString.call(arr)); //"[object Array]"
标签:
原文地址:http://www.cnblogs.com/solomonhit/p/4422101.html