Today, when I read the javascript advanced Program Design book, I saw an article on the security scope. Next I will write about the security scope usage of js constructor based on my own knowledge.
Let's take a test. The summary is as follows:
Javascript is an extremely flexible language...
In many cases, js is not executed as we expected.
Js constructor is to use new to operate a function. When using new, the this pointer of the function will point to the scope of the current object.
The Code is as follows: |
Copy code |
Function Person (name, age, job ){ This. name = name; This. age = age; This. job = job; } Var p = new Person ("siren", 24, "php "); |
In the above example, a new object is created with new. The this pointer of this function will point to the scope of p, so there is no problem.
But what if we don't need to create a new object?
The Code is as follows: |
Copy code |
Function Person (name, age, job ){ This. name = name; This. age = age; This. job = job; } Var p = Person ("siren", 24, "php "); Alert (window. name); // siren Alert (window. age); // 24 Alert (window. job); // php |
In this case, p is an undefined, and the this pointer of Person points to the window scope.
Why?
Because the constructor is called as a common function and ignores the new operator, this object is parsed into a window object due to the late binding of this object.
This problem will overwrite the properties of the window field.
How can this problem be solved?
In fact, in js, there is also the same keyword instanceof as php.
It is used to check whether the object is an instance.
The Code is as follows: |
Copy code |
Function Person (name, age, job ){ If (this instanceof Person ){ This. name = name; This. age = age; This. job = job; } Else { This = new Person (name, age, job ); } } Var p = Person ("siren", 24, "php "); Alert (p. name); // siren Alert (p. age); // 24 Alert (p. job); // php |