This day saw the front-end online on the topic of js, one of the topics is very interesting. As follows
1 var a = b =10; 2 (function() {3 var a = b = +; 4 })(); 5 Console.log (a); 6 Console.log (b); 7 Q: What is the output of a =? b =?
What do you think is the result?
Perhaps the vast majority of people and I think it is the same . however, the answer is 10, 20, don't worry we first to slowly analyze (*^__^*) hehe ...,
1. First row of var a = b = ten; Is the use of the even operator, even if the operator is right-to-left so similar to b = ten; a = b; or a = (b = ten); This order is assigned from right to Left.
The variable a is declared with var and is assigned a value so it is a local variable , but B is a global variable that is not declared and is assigned DIRECTLY. So when you use a hyphen operator, you don't have a global variable or a variable that uses the back end of the scope chain.
2. Starting with the second line use the anonymous function implementation to mimic the Block-level action ( private scope ): The variable declared inside will be destroyed at the end of the function unless used externally. The third line carries on the operation, first uses the external local variable b,b = 20; And then we re-declared a variable A.
This is a cross-level scope to re-declare the A and the outside without any relation, you can think of it as any other variable than the Var x;
|
then var a = b; after initialization, A is 20.
3. Line fourth declares that an anonymous function is defined and executed, and the variable a created in the private scope is destroyed immediately after it has ended. so the last change is only the value of the external variable B.
When the strike is over, let's look at a similar operation assignment Problem. As follows
1 think about what the result is, right? 2var a = {n:13var b = a; 4 a.x = a = {n:2}; 5 Q: Console.log (a.x); 6 Console.log (b.x);
Perhaps some people see the answer and doubts, see the above feeling oneself master, and then this question but have unexpectedly (⊙﹏⊙) b;
As a result , I do not know if there is a small partner to correct it ....
Let's analyze It again.
1. First the second line declares and uses the object literal syntax to create an object with property N = 1, The third row declares the variable b, and assigns the object reference of A to B. So now the variables B and a point to the same object, i.e. they are now Shared.
2. Line fourth question came,a.x = a = {n:2}; first create an object {n:2} and send his reference to variable A. Because A.x retains a reference to {n:1} before execution, adding a property A to the original object is a reference to {n:2}
And a now {n:2} does not have an X attribute so it is undefined, and still points to the original reference so b.x = a;
// true
May be a little unclear, I hope you can speak your point of view, but also hope that you can understand JS more deeply
Something about the value of the hyphen in Javascript.