Understanding the JavaScript finishing page 1/2 _ javascript skills

Source: Internet
Author: User
There are only two basic elements in the programming world: Data and code. The programming world presents infinite vigor and vitality in the tangle of data and code. There are only two basic elements in the programming world: Data and code. The programming world presents infinite vigor and vitality in the tangle of data and code.

Data is inherently quiet, and always wants to keep its inherent nature; while code is inherently lively, always wants to change the world.

As you can see, the relationship between data codes is surprisingly similar to that between material and energy. Data is also inertial. If there is no code to exert external force, she always keeps her original state. Code is like energy. The only purpose of its existence is to try to change the original state of data. When the code changes the data, it will also affect or change the original trend of the code because of data resistance. Even in some cases, data can be converted into code, but code may be converted into data. There may also be a digital conversion equation in the form of E = MC2. However, in the conflict and unified operation between data and code, the rules of the computer world can always be reflected. These rules are the logic of the program we write.

However, because different programmers have different world views, the data and code seem to be different. As a result, programmers of different world views use their respective methodologies to promote the evolution and development of the programming world.

As we all know, today's most popular programming ideology is the idea of object-oriented programming. Why can Object-oriented Thinking quickly become popular in the programming world? For the first time, object-oriented thinking combines data and code into a unity and presents it to programmers with a simple object concept. In this case, the original messy algorithms, subprograms, and obscure complex data structures are divided into clear and orderly object structures, this makes it clear that data and code are in a mess in our hearts. We can have a clearer mind and explore a more vast programming world at the height of another thought.

One day after Wu zuhong taught "Object truth Sutra", he said to the disciples, "after the lecture, I must have some insights, please write a token for them ". The great disciple, Shen Xiu, was recognized by everyone as the Senior brother with the highest understanding. His nephew wrote: "The body is an object tree, and his heart is as clear as a kind of vision. !". It immediately caused a sensation among the teachers and brothers. Only after the fire-headed Monk was able to see it, he sighed and wrote on the wall: "The object has no root, and the type is invisible. There is no such thing as where to make the dust ?". Then I shook my head and went away. Everyone who reads Hui Neng's notebook said, "What is wrong with writing? I can't understand it ". Master Hong endured the outstanding poetry and nodded. Then he shook his head silently. On the night of that day, Hong endured quietly calling Hui Neng to his Zen Room, teaching him the true story of the software he had collected for many years, and letting him escape by moonlight...

Later, Hui Neng met master's high hopes and created another vast sky of Zen in the south. Among the software that Hui Neng took in that year, there was a JavaScript truth!

Simple regression

To understand JavaScript, you must first put down the concepts of objects and classes and return to the source of data and code. As mentioned above, there are only two basic elements in the programming world: Data and code, and these two elements have an ambiguous relationship. JavaScript simplifies data and code to the most primitive level.

The data in JavaScript is concise. Simple data only includes undefined, null, boolean, number, and string, and complex data contains only one type, namely, object. This is like the Chinese classical simple materialism, which classifies the most basic elements of the world as gold, wood, and fire. Other complex materials are composed of these five basic elements.

The code in JavaScript is only reflected in one form, that is, function.

Note: The above words are in lower case. Do not confuse them with JavaScript built-in functions such as Number, String, Object, and Function. You know, JavaScript is case sensitive!

Any JavaScript identifier, constant, variable, and parameter is only one of the unfined, null, bool, number, string, object, and function types, that is, the type indicated by the return value of typeof. There are no other types.

Let's talk about the simple data type first.

Undefined: indicates that everything is unknown, and the Code cannot be processed even if nothing is found.
Note: typeof (undefined) returns undefined.
Undefined can be assigned to any variable or attribute, but it does not mean that the variable is cleared. Instead, an attribute is added.

Null: there is such a concept, but there is nothing. None seems to exist. It is hard to imagine, but it can already be processed using code.
Note: typeof (null) returns an object, but null is not an object, and a variable with a null value is not an object.

Boolean: Yes. If not, there is no doubt. Right is right, right is wrong, absolutely clear. It can be processed by code or control the code process.

Number: linear objects with distinct sizes and order. It facilitates code batch processing and controls code iteration and loop.
Note: Both typeof (NaN) and typeof (Infinity) return number.
NaN participates in any numerical calculation. The structure is NaN, and NaN! = NaN.
Infinity/Infinity = NaN.

String: a rational object oriented to humans, rather than machine signals. Human-machine information communication, code understanding of people's intentions, and so on, all rely on it.

Simple types are not objects, and JavaScript does not assign the objectization capability to these simple types. Identifiers, variables, and parameters that are directly assigned a simple type constant value are not an object.

The so-called "objectization" means the ability to organize data and code into complex structures. In JavaScript, only the object type and function type provide the objectization capability.

No class

Object is the object type. In JavaScript, no matter how complex the data and code are, they can be organized into objects in the form of objects.

But JavaScript does not have the concept of "class!

For many object-oriented programmers, this is probably the most difficult to understand in JavaScript. Yes. In almost any object-oriented book, the first thing to talk about is the concept of "class", which is the pillar of object-oriented. This suddenly does not have a "class", we feel as if we have no spiritual pillar at once, and have no master. It seems that it is really not easy to put down objects and classes to reach the realm of "No root object, no invisible type.

Now let's look at a JavaScript program:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


At the beginning, this JavaScript program produced a life object. life was just a walking object, without any attributes or methods. In its first life, it had a body attribute and a say method, which looked like an "egg ". In the second life process, it grew "tail" and "Cheek", with the tail and gill attributes, apparently it was a "Cockroach ". In the third life process, its tail and gill attributes disappear, but "Four legs" and "lung" grow, with the legs and lung attributes, finally, it becomes a "frog ". If your imagination is rich, you may also turn it into a handsome "Prince" and marry a beautiful "princess" or something. However, after reading this program, consider the following question:

Do we need classes?

Do you remember the fairy tale of "Xiao looking for Mom? Maybe last night, your child just fell asleep in this beautiful fairy tale. In the process of its own type evolution, the cute little girl gradually becomes the same "class" as her mother, thus finding her mother. The programming philosophy contained in this fairy tale is that the "class" of an object is evolved from nothing to existence and eventually disappears into the invisible world...

"Category" can indeed help us understand the complex real world, and the chaotic real world also needs to be classified. However, if our thinking is constrained by "Classes", "Classes" will become "tired ". Imagine if a life object is defined as a fixed "class" at the beginning, can it still evolve? Can the cockroach still become a frog? Can you tell the children the story of Xiao looking for his mother?

Therefore, there is no "class" in JavaScript. classes have been made invisible and integrated with objects. It is precisely because the concept of "class" is put down that JavaScript objects have no vitality in other programming languages.

If, at this time, you begin to feel something deep in your heart, then you have gradually started to understand the JavaScript Zen machine.

Magic of functions

Next, let's discuss the magic of JavaScript Functions.

JavaScript code has only one function form, and function is the function type. Maybe other programming languages also have code concepts such as procedure or method, but there is only one function form in JavaScript. When we write the next function, we just create a function-type entity. See the following program:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


After running this code, you can see that typeof (myfunc) returns the function. The above function syntax is called "definition". If we rewrite it into the following "variable", it will be easier to understand:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


A variable myfunc is defined here, and its initial value is assigned to the entity of a function. Therefore, typeof (myfunc) returns a function. In fact, the writing of these two functions is equivalent, except for a slight difference, the internal implementation is exactly the same. That is to say, the JavaScript Functions we write are just a named variable. The variable type is function, and the value of the variable is the code body of the function we compile.

Clever, you may immediately ask: since a function is just a variable, the variable can be assigned a value at will and used anywhere?

Let's take a look at the following code:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


The result of running this program tells us: the answer is yes! After the function is called for the first time, the function variable is assigned a new function code body, so that different outputs appear when the function is called for the second time.

Now, let's change the above Code to the first defined function form:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


The two functions with identical signatures should be invalid in other programming languages. But in JavaScript, that's right. However, after the program runs, it finds a strange phenomenon: both calls are only the value output in the last function! Obviously, the first function does not play any role. Why?

Originally, the JavaScript execution engine did not analyze and execute programs one by one, but analyzed and executed the programs one by one. In addition, during the analysis and execution of the same program, the defined function statements are extracted for priority execution. After the function definition is executed, other statement code is executed in order. That is to say, before myfunc is called for the first time, the Code logic defined by the first function statement has been overwritten by the second Function Definition Statement. Therefore, the last function logic is executed for both calls.

If you divide the JavaScript code into two sections, for example, write them in an html file, and useThe tag is divided into two parts:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


At this time, the output is in order, and it also proves that JavaScript is indeed executed in segments.

The definition function statements in a piece of code are executed first, which seems to be a bit like the compilation concept of static language. Therefore, this feature is also called "pre-compilation" of JavaScript ".

In most cases, we do not need to tangle these details. As long as you remember, the code in JavaScript is also a kind of data that can be assigned and modified at will, and its value is the logic of the Code. However, unlike general data, a function can be called for execution.

However, if JavaScript functions only have this line, it is strange to compare it with C ++ function pointers, DELPHI method pointers, and C # delegation! However, the magic of JavaScript Functions is also reflected in two aspects: first, the function type itself has the ability to be object-oriented, and second, the ability to combine function functions with object detachment.

Wonderful object

Let's first talk about the function's objectization capability.

Any function can dynamically add or remove attributes. These attributes can be simple, object, or other functions. That is to say, a function has all the features of an object. You can use a function as an object. In fact, a function is an object, but a bracket "()" operator is added to an ordinary object. This operator is used to execute the function logic. That is, the function itself can also be called, but generally the object cannot be called, in addition to the same. See the following code:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


In this Code, after the Sing function is defined, the author and poem attributes are dynamically added to the Sing function. Set author and poem attributes to different authors and verses, and different results will be displayed when you call Sing. This example uses a poetic style to help us understand that JavaScript Functions are the essence of objects and the beauty of JavaScript.

Well, as described above, we should understand that all functions are of the same type as objects, which are called "objects ". We can really look at these "objects" like this, because they have both "attributes" and "methods. However, the following code creates new questions:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


Yes, objects and functions can be accessed and processed using attribute names or method names as subscripts like arrays. So should it be regarded as an array or an object?

As we know, arrays should be regarded as linear data structures. Linear data structures generally have certain rules and are suitable for uniform batch iteration operations, which is a bit like a wave. Objects are discrete data structures, which are suitable for describing scattered and personalized things, a bit like particles. Therefore, we can also ask: is the object in JavaScript a wave or a particle?

If there is an object quantum theory, the answer must be: wave-particle binary!

Therefore, functions and objects in JavaScript have both Object Features and array features. The array here is called a "Dictionary", a set of name-value pairs that can be scaled at will. In fact, the internal implementation of objects and functions is a dictionary structure, but this dictionary structure shows a rich appearance through rigorous and sophisticated syntax. Just as quantum mechanics uses particles in some places to explain and solve problems, while in other places it uses waves to explain and handle problems. You can also choose whether to use objects or arrays to explain and handle problems as needed. As long as you are good at understanding these wonderful features of JavaScript, you can write a lot of simple and powerful code.

Drop object

Let's take a look at the detached combination of function and object.

In the object-oriented programming world, the organic combination of data and Code constitutes the concept of objects. With the object, the programming world has been divided into two parts: one is the world inside the object and the other is the world outside the object. Objects are inherently selfish, and the world outside is not allowed to access objects. The object also has a generous aspect. It provides external attributes and methods and serves others. However, here we want to talk about an interesting question: "Object self-consciousness ".

What? Didn't you hear it wrong? Is the object self-conscious?

This is indeed the first time that many programmers have heard of it. However, please take a look at C ++, C # and Java's this, DELPHI's self, and VB's me. Maybe you will suddenly realize it! Of course, you may just say "but that's all.

However, when the object divides the world into two parts, the object's "self" is generated. "Self-Consciousness" is the most basic feature of life! It is precisely because of the powerful vitality of objects that the programming world is full of infinite vigor and vitality.

However, the object's "Self-Consciousness" brings us happiness, but also brings us pain and troubles. We have given too many desires to objects and always hope they can do more. However, the selfishness of objects makes them compete for system resources. The object's self-sufficiency makes the object complicated and bloated. The object's self-deception often brings lingering errors and exceptions. Why are there so many pains and troubles?

To this end, a person, under the tree of the object, thought for days and finally realized that the pain of life came from desire, but the root of his desire came from self-consciousness. So he put down his "self" and became a Buddha under the tree of the object. Then he began to popularize all beings and spread the truth. His name is Sakyamuni, and "JavaScript Sutra" is one of the scriptures he wrote.

This is also available in JavaScript, but this is different from this in C ++, C #, Java, and other languages. In general, this in programming language is the object itself, but this in JavaScript is not necessarily! This may be me, you, maybe him, or me, therefore, the original "self" cannot be used to understand the meaning of this in JavaScript. To this end, we must first put down the "self" of the original object ".

Let's look at the following code:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


From the code above, we can see that the same function can be called from different angles. this is not necessarily the object to which the function belongs. This is just a concept when any object and function elements are combined. It is a combination that is more flexible than the default combination of general object languages, and is more detached and free-of-charge.

In JavaScript Functions, you can only regard this as the "this" object to be served. This is a special built-in parameter. Based on this parameter, you can access the attributes and methods of the "this" object, but cannot assign values to this parameter. In the general object language, this in the method body code can be omitted. By default, Members are "self" first. But JavaScript is different. Because there is no "self", this cannot be omitted when accessing the "this" object!

JavaScript provides multiple forms and means to pass this parameter, such as BillGates. whoAmI () and SteveJobs. whoAmI () is the most formal form for passing the this parameter. In this case, this is the object to which the function belongs. In most cases, we seldom use the called form of the fairy Buddha. But we only need to understand that the "self" of JavaScript is different from the "self" of other programming languages. This is a put-down "self", which is a unique world view of JavaScript.

Object sketch

I have already talked about many topics, but I forgot to discuss a basic question: how to create objects?

In the previous example, we have involved object creation. We use a form called JavaScript Object Notation (JSON), which translates into Chinese as "JavaScript Object Notation ".

JSON provides a very simple method for creating objects. For example,
Create an object without any attributes:
Var o = {};
Create an object and set attributes and initial values:
Var person = {name: "Angel", age: 18, married: false };
Create an object and set attributes and methods:
Var speaker = {text: "Hello World", say: function () {alert (this. text )}};
Create a more complex object and nest other objects and object arrays:
Var company =
{
Name: "Microsoft ",
Product: "softwares ",
Chairman: {name: "Bill Gates", age: 53, Married: true },
Employees: [{name: "Angel", age: 26, Married: false}, {name: "Hanson", age: 32, Marred: true}],
Readme: function () {document. write (this. name + "product" + this. product );}
};
The JSON format is the list of projects included with the large "{}". Each project is separated by a comma (,), and the project is a colon (:):. This is a typical dictionary representation, and again shows that the objects in JavaScript are dictionary structures. No matter how complex an object is, it can be created and assigned a value by a JSON code.

In fact, JSON is the best serialization form for JavaScript objects, which is simpler and more space-saving than XML. An object can be a JSON string and transmitted and exchanged freely between networks. To convert the JSON string into a JavaScript Object, you only need to use the eval function, a powerful digital conversion engine, to immediately obtain a JavaScript Memory Object. Because of JSON's simplicity and simplicity, she became a dazzling star on the AJAX stage.

JavaScript is like this. It expresses object-oriented seemingly complex things in a concise form. Remove the rich makeup of the object, and clear the eyes of the object!

Constructor

Now, let's discuss another object creation method.

In addition to JSON, we can use the new operator in JavaScript to create an object in the form of a function. For example:
Function MyFunc () {}; // defines an empty function
Var anObj = new MyFunc (); // use the new operator and use the MyFun function to create an object.
This method of creating objects in JavaScript is really interesting. How can we understand this method?

In fact, the above Code can be rewritten into this equivalent form:
Function MyFunc (){};
Var anObj ={}; // create an object
MyFunc. call (anObj); // use the anObj object as the this pointer to call the MyFunc function.
We can understand that JavaScript first creates an object with the new operator, and then calls the subsequent function as the this parameter. In fact, this is what JavaScript does internally, and any function can be called like this! But from the form of "anObj = new MyFunc ()", we can see another familiar figure. Isn't C ++ and C # creating objects like this? It turns out that things are the same as things!

As you may see, why can't we regard this MyFunc as a constructor? Congratulations! Correct! The same is true for JavaScript! See the following code:

The Code is as follows:


1 function Person (name) // constructor with Parameters
2 {
3 this. name = name; // assign the parameter value to the attribute of this object.
4 this. SayHello = function () {alert ("Hello, I 'm" + this. name) ;}; // defines a SayHello method for this object.
5 };
6
7 function Employee (name, salary) // subconstructor
8 {
9 Person. call (this, name); // pass this to the parent constructor.
10 this. salary = salary; // you can specify the salary attribute of this.
11 this. ShowMeTheMoney = function () {alert (this. name + "$" + this. salary) ;}; // Add the ShowMeTheMoney method.
12 };
13
14 var BillGates = new Person ("Bill Gates"); // create a BillGates object using the Person Constructor
15 var SteveJobs = new Employee ("Steve Jobs", 1234); // create a SteveJobs object using the Empolyee Constructor
16
17 BillGates. SayHello (); // display: I'm Bill Gates
18 SteveJobs. SayHello (); // display: I'm Steve Jobs
19 SteveJobs. ShowMeTheMoney (); // display: Steve Jobs $1234
20
21 alert (BillGates. constructor = Person); // display: true
22 alert (SteveJobs. constructor = Employee); // display: true
23
24 alert (BillGates. SayHello = SteveJobs. SayHello); // display: false


This Code shows that a function can be used not only as a constructor, but also as a parameter. You can also add members and methods to an object. In the second row, the Employee constructor calls the Person constructor using the this received by itself as the parameter, which is equivalent to calling the base class constructor. Rows 21st and 22 also indicate that BillGates are constructed by Person, while SteveJobs are constructed by Employee. The constructor attribute of the object also specifies the specific functions used to construct the object!

In fact, if you want to treat a function as a "class", she is a "class" because she already has the features of "class. Isn't it? Her son has the same features, and the constructor has the same name as the class!

Current 1/2 page12. Next page

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.