javascript - Are objects defined without using var within js functions local objects?
typecho
typecho 2017-06-14 10:53:31
0
4
936

The object that is not defined using var in the function should be a global object.
On page P71 of the Little Red Book, it is said that when obj is rewritten internally in the function, the object reference becomes a local object. I don’t understand~~

typecho
typecho

Following the voice in heart.

reply all(4)
洪涛

I specially took out my little red book. This section talks about passing parameters by value; then, objects are passed by value, and what is passed is the pointer to the location of the object. So, in the first step, it is easy to understand if there is a 'name' attribute of 'chen'.
Because obj is a parameter of the function, the actual meaning is that within the function, var has an obj. Later, after the function is executed, it will be destroyed. Maybe you can understand it better after reading the execution environment and scope later. Then, when obj = new Object() , the value of obj is no longer the pointer of the original person object.
Of course, if you replace the second line of code with 'obj1', you will have the effect of the global declaration you mentioned. (Answer the question very seriously)

学霸

What you write in the function you define like this is just a formal parameter, not an actual parameter, let alone global and local parameters. . . . . . . . . . . . . .

女神的闺蜜爱上我

obj is a parameter

淡淡烟草味

After reading the reference answers given by netizens, I thought about it for a while, and I roughly understand it. I don’t know if it’s right or not, but I think I’m pretty close!
The parameters of all functions in ECMAScript are passed by value
So when the person object is passed to setName() in the form of actual parameters, the pointer of the person object is copied to setName()
Assume that the original pointer to the person object is number one , the copied pointer is No. 2
These two pointers point to the person object at the same time
So when obj.name="chen"; is executed within the function, a name attribute will be added to the person object according to the No. 2 pointer
But when executing When obj=new Object();, the second pointer will point to a new object instead of the original person object
So when obj.name="long"; is executed, the name attribute of the person object will not be changed
console .log(person.name); will return "chen"
and obj is a formal parameter, not an actual parameter. There is no global or local distinction. It will be destroyed after the function is executed, that is, there is no longer pointer number two. There is no pointer to the name attribute "long".

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template