Baidu HR to give the JS face questions

Source: Internet
Author: User

Say the following code to run the results

var a = {N:1}
var B = A;
a.x = a = {N:2}
Console.log (a.x);
Console.log (b.x)


Output:
Undefined
N:2


parsing:
var a = {N:1}//defines variable A as a new object, and the new object has an n member with a value of 1
var B = A; Define variable B, and let B also refer to the object of variable a
After these two sentences, both variables A and B refer to the object {N:1}

The following sentence is the key to the problem
a.x = a = {N:2}
A.x = Represents the x member of the object {N:1} to which a reference is to be assigned
In fact, variable B also references this object {N:1}
At this point, the JavaScript engine first adds an empty x member to {N:1}, namely: {n:1,x:undefined}
What is the value of the next assignment to {n:1,x:undefined}.x?
The value to assign is a = {N:2}
That is, let variable a refer to a new object {N:2} first
And then assign the new value of a to {n:1,x:undefined}.x
So the original object becomes the {N:1,x:{n:2}}
Because variable b always references that original object, the value of B is {N:1,x:{n:2}}
Because variable A is given a new object, the value of a is {N:2}

These two lines are console output.
Console.log (a.x); The object referenced by variable A is {N:2}, and there is no X member, so the output undefined
Console.log (b.x); The object referenced by variable b is {N:1,x:{n:2}}, so the output {N:2}

Web front-end course tools and e-books are required, plus 22 groups of 120342833

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.