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~~
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 anobj
. 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, whenobj = 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".