js连等赋值分析

<script>

    var a = {n:1};

    a.x = a = {n:2};

    console.log(a.x);   //undefined

    var b = {n:1};

    b = b.x = {n:2};

    console.log(b);     //object{n:2}

    console.log(b.x);   //undefined

</script>

三个输出是什么原理?谢谢


慕标5832272
浏览 499回答 1
1回答

Qyouu

a.x&nbsp;=&nbsp;a&nbsp;=&nbsp;{n:2};等式从右边开始计算,但是在计算之前先求得各个变量的地址。即a.x中的a指向{n:1}这个对象,而连等式中的a指向{n:2}这个对象,即运算完成后,a指向{n:2},因此在连等赋值后打印a.x是undefined。用下面这个例子更明白点&nbsp;var b = {n:1};&nbsp; &nbsp; b = b.x = {n:2};&nbsp; &nbsp; console.log(b);&nbsp; &nbsp; &nbsp;//object{n:2}&nbsp; &nbsp; console.log(b.x);&nbsp; &nbsp;//undefined第二个例子同样的道理,等式中间b.x中的b指向的是{n:1}这个对象,然而等式左边的b指向了{n:2}这个对象,即运算完成后,b指向{n:2},因此后来打印的b为{n:2},而b.x即为{n:2}[x],所以是undefined
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript