Javascript Note: deeply analyzes the creation (medium) of objects in Javascript)

Source: Internet
Author: User

In-depth analysis of the creation of objects in Javascript this small series is the most popular in my blogArticleSome bloggers urged me to finish my next article. Yesterday and today I found that an article could not finish my next half, so I divided the next article I was going to write into two parts.

In the previous article of this topic, I talked about three ways to create objects. Finally, I understood how to create javascript objects by analogy with Java Object-oriented thinking. If I have created the core object based on the title, I have already explained the problem. However, when I wrote the last article, I always felt that I was missing something, And I lacked the in-depth analysis in my title. Creating a small JavaScript Object contains an extremely broad extension of the technology. When it comes to actual development, there is not a certain accumulation of divergent knowledge, and we think we will encounter problems that are hard to understand, in the middle and lower sections, I want to open this question from the knowledge development I mentioned earlier.

1. Another understanding of class attributes and Methods

In the previous article, I wrote a sentence: "1. class attributes and Methods: object initialization can be considered as class attributes and methods. This definition is widely used in jquery."

You know that a class in Java can have static attributes and methods. You can access these attributes and methods without instantiating the class objects, but does JavaScript simulate this feature only through object initialization? OtherwiseProgramming LanguageClass Method and attribute comparison standard is called:The attributes and methods defined by the static scope can be accessed from the same location at any time.. In fact, strictly speaking, JavaScript does not have a static scope. object initialization can produce this effect, but it is too intuitive. As I mentioned in the previous blogThe class definition is omitted during the Javascript language design. Instead, the class definition is assigned to the constructor.So we can think about it like this. To make JavaScript have class attributes and methods, the best form of presentation is to make the constructor have attributes and Methods. Let's take a look at the following:Code:

 

  function  jsobj () 
{< br> This . sayhello = function () {
console. log ('Hello world !!! ');
}< br>
jsobj. whosay = function () {
console. log ('sharpxiajun say hello World !!! ');
}< br>
jsobj. whosay ();
var OBJ = New jsobj (); /// sharpxiajun say hello World !!!
obj. sayhello (); /// Hello world !!!

This way of writing reflects the static attributes of the class and the features of the method will be clearer. Some people recently told me that the object-oriented approach in Javascript has now become a kind of object-oriented standard, some new languages now use JavaScript to design their own object-oriented mechanisms, but I am willing to use the Java method as the standard method of object-oriented, javascript is implemented in a simulated way. If JavaScript object-oriented is understood as a new standard, inertial thinking may make it difficult for me to have a clearer understanding of JavaScript object-oriented practices. If the principle used by the code above is that functions in JavaScript are objects, you can assign values or assign methods to them. This problem is very simple and easy to understand. Here I come up with this code to tell you that when I am reading the source code of some classic frameworks, some design ideas use this method, but I didn't understand them as static variables, so some code didn't understand them.

2. Questions about the this pointer

This is the most important concept of JavaScript. Its usage is the key to understanding the essence of JavaScript. Let's take a look at the following sentence, which shows the essence of this usage:

Keyword: This is used in object methods. This always points to the object that calls this method.

This statement indicates that this is an object method, which contains two content: object and method. The method belongs to the object. The sample format is:

 

VaROBJ = {};//Or var OBJ = new object (); the two are equivalent.
OBJ. Nation = 'China ';
OBJ. say1 =Function()
{
Console. Log (obj. Nation );
}
OBJ. say2 =Function()
{
Console. Log (This. Nation );
}

OBJ. say1 ();//China
OBJ. say2 ();//China

The result is the same. This shows that this is used in object methods. This always points to the object that calls this method. This is a standard definition of this usage, but it is really hard to understand this concept. I will leave this definition aside and list the usage of this.

Usage 1: Use in Functions

 

FunctionJsobj ()
{
This. Nation = 'China ';
Console. Log (This. Nation );
}
Jsobj ();//China

Does this point to the jsobj function? The answer is no. This points to the window. Check the following code:

 

FunctionJsobj ()
{
This. Nation = 'China ';
Console. Log (This. Nation );
}
Jsobj ();//China

Console. Log (nation );//China
Console. Log (window. Nation );//China
Console. Log (This. Nation );//China

If you see the effect, it points to the window. I think some kids shoes may not quite understand why. It doesn't matter. This question will lead to what I will talk about in the next section.

Usage 2: Call an object Method

This usage is similar to the usage of the this pointer. The Code is as follows:

 

 
FunctionSay ()
{
Console. Log (This. Nation );
}

VaROBJ = {};
OBJ. Nation = 'China ';
OBJ. objsay = say;
OBJ. objsay ();//China

Usage 3: Call the constructor

When talking about JavaScript constructor, I will repeatedly emphasize a basic knowledge:Constructor in Javascript contains the class features. The code I wrote is as follows:

 

FunctionJsobj ()
{
This. Nation = 'China ';
}
VaROBJ =NewJsobj ();
Console. Log (obj. Nation );//China

This nation is definitely not a window. Do you believe it or not? We can test it:

 

VaRNation = 'usa ';
FunctionJsobj ()
{
This. Nation = 'China ';
}
VaROBJ =NewJsobj ();
Console. Log (obj. Nation );//China
Console. Log (nation );//USA

Usage 4: This

Apply () is a method of a function object. Its function is to change the object called by the function. Its first parameter indicates the object called by the function after the change. Therefore, this is the first parameter. The test code is as follows:

 

VaRNation = 'usa ';
FunctionSay ()
{
Console. Log (This. Nation );
}
VaROBJ = {};
OBJ. Nation = 'China ';
OBJ. objsay = say;
OBJ. objsay. Apply ();//USA
OBJ. objsay. Apply (OBJ );//China

When the apply () parameter is null, The Global object is called by default. Therefore, the running result is USA, which proves that this is a global object. When the object obj is input to apply, this points to the object OBJ, and the running result is China.

3. Execution Environment and scope

In the summary above, I raised a question when I used this in Javascript. Why does this point to window? To explain this question, there will be a very important concept in JavaScript.Execution Environment and scope.

The first thing we talk about is the execution environment. What is the execution environment?In JavaScript, the execution environment is divided into two types: global environment and local environment. The shared methods and attributes on the entire page are in the global environment, the execution environment in function {} is a local environment. The execution environment defines other data that variables or functions have the right to access and determines their respective behaviors, each execution environment defines a variable object related to it. All variables and functions defined in the environment are stored in this object, although the code we write cannot access this object, however, the parser will use it in the background when processing data..

The global execution environment is also the peripheral execution environment, which is within the scope of the Web browser, its global range is different from that of JavaScript ),The global execution environment is considered a window object. Therefore, global variables and functions are created as methods and properties of the window object., The Global execution environment knows the applicationProgramExit, for example, close the Web page or the browser before it is destroyed. The local environment uses the function object as the correlated object.

The javascript language defines the concept of a global execution environment and a local execution environment, which generates an extremely important application:Scope chain. When the code is executed in an environment, it creates a scope chain composed of variable objects. Its purpose is to ensure that the execution environment has the right to access all variables and functions in an orderly manner. The front end of the scope chain is always the variable object in the environment where the code is currently executed. If the environment is a function, the activity object is used as the variable object. The activity object contains only one variable at the beginning, which is the arguments object. Arguments does not exist in the global environment, the next object in the scope chain comes from the external environment that contains the previous object, and the next variable object comes from the next stage, and so on, continues to the global environment, the global environment is always the last object of the scope chain.

Well, check whether this explanation is a bit dizzy. I want to think about it from another angle. In JavaScript, all attributes and Methods belong to a certain object, in JavaScript, all method or attribute calls are obj. method (), obj. name Style. If the calling object cannot be found when calling a property or method in the program code, the Javascript parser will find it in the upper-level scope of the function scope until the window global environment, if it cannot be found, it is granted to the window object by default.

Well, let's write so much about today's content. I really didn't expect that the creation of simple JavaScript objects can extend so much knowledge. I think this kind of research method is quite good, there have been too many Java projects recently (I want to start a new series recently and I have always wanted to develop Android series, but someone told me that I have limited energy, I still need to write something I haven't written). I don't have enough passion to write the commit Crip. I really hope to have a full-time front-end environment, but Java is also very interesting, after talking with Boyou recently, I became more motivated to write the three javaee frameworks and cheer myself up.

 

 

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.