Details about the security scope usage of js Constructor

Source: Internet
Author: User

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

Related Article

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.