There are only two basic elements in the programming world, one is data and the other is code. The world of programming shows infinite vitality and vitality in the inextricable entanglement of data and code.
Data is naturally quiet and always wants to maintain its inherent nature; while code is naturally lively and always wants to change the world.
You see, the relationship between data codes is surprisingly similar to the relationship between matter and energy. Data also has inertia. If there is no code to exert external force, it will always maintain its original state. Code is like energy. The only purpose of its existence is to work hard to change the original state of the data. When the code changes the data, it will also in turn affect or change the original trend of the code due to the resistance of the data. Even in some cases, data can be converted into code, and code may be converted into data. There may be a digital conversion equation similar to E=MC2. However, it is in this contradictory yet unified operation between data and code that the laws of the computer world can always be reflected. These laws are exactly the program logic we write.
However, because different programmers have different world views, these data and codes look different. As a result, programmers with different worldviews use their own methodologies to promote the evolution and development of the programming world.
As we all know, the most popular programming idea today is object-oriented programming. Why can object-oriented ideas quickly become popular in the programming world? Because object-oriented thinking combines data and code into a unity for the first time and presents it to programmers with a simple object concept. This suddenly divides the original messy algorithms and subroutines, as well as the entangled complex data structures, into clear and orderly object structures, thus clarifying the messy knot of data and code in our hearts. We can have a clearer mind and explore the vaster programming world from another level of thinking.
One day after the Fifth Patriarch Hongren finished teaching the "Object True Sutra", he said to all his disciples: "The lecture has been finished. I think you should have some insights. Please each write a verse to read. ". The eldest disciple, Shenxiu, is recognized as the senior brother with the highest understanding. His verse reads: "The body is like an object tree, and the mind is as bright as its kind. Wipe it diligently and don't let it stir up dust!". As soon as this verse came out, it immediately caused a sensation among the brothers. Everyone said it was so well written. Only the fire-headed monk Hui could look at it, sighed softly, and wrote on the wall: "The object has no roots, and the type is invisible. There is nothing in the first place, so where can it cause dust?" Then he shook his head and walked away. Everyone who read Hui Neng's gatha said, "It's written in such a mess that I can't understand it." Master Hongren read Shenxiu's verse and nodded in praise, and then looked at Huineng's verse and shook his head silently. That night, Hongren quietly called Huineng to his meditation room, taught him the software scripture that he had treasured for many years, and then asked him to escape overnight under the moonlight...
Later, Huineng really didn't Living up to Master's high expectations, he created another vast sky for Zen Buddhism in the south. One of the software scriptures that Huineng took away was the "JavaScript Scripture"!
Return to simplicity
To understand JavaScript, you must first let go of the concepts of objects and classes and return to the origins of data and code. As mentioned before, the programming world has only two basic elements: data and code, and these two elements are intertwined. JavaScript simplifies data and code to the most primitive level.
Data in JavaScript is very simple. There are only five types of simple data: undefined, null, boolean, number and string, while there is only one type of complex data, namely object. This is like classical Chinese simple materialism, which classifies the most basic elements of the world as metal, wood, water, fire, and earth, and other complex substances are composed of these five basic elements.
The code in JavaScript is only reflected in one form, which is function.
Note: The above words are all lowercase, do not confuse them with JavaScript built-in functions such as Number, String, Object, and Function. You know, the JavaScript language is case-sensitive!
Any JavaScript identifier, constant, variable and parameter is just one of the unfined, null, bool, number, string, object and function types. That is, the type indicated by the return value of typeof. There is no other type besides this.
Let’s talk about simple data types first.
undefined: represents all unknown things, nothing, unimaginable, and the code cannot handle it.
Note: Typeof (undefined) return is also undefined.
You can assign undefined to any variable or property, but it does not mean that the variable is cleared, but it will add an additional property.
null: There is a concept, but nothing. There seems to be something within nothing, and nothing within something. Although it is difficult to imagine, it can already be handled with code.
Note: Typeof (Null) returns Object, but NULL is not Object, and variables with NULL values are not Object.
boolean: Yes is, no is no, there is no doubt. Right is right, wrong is wrong, absolutely clear. It can be processed by the code and can also control the flow of the code.
Number: Linear things, clear in size and order, numerous but not chaotic. It facilitates batch processing of code, and also controls the iteration and looping of code.
Note: Typeof (nan) and Typeof (Infinity) both return Number.
The structure of NaN participating in any numerical calculation is NaN, and NaN != NaN.
Infinity / Infinity = NaN.
string: Rational things for humans, not machine signals. Human-computer information communication, code understanding of human intentions, etc. all rely on it.
Simple types are not objects, and JavaScript does not give these simple types the ability to objectify. Identifiers, variables, and parameters that are directly assigned constant values of simple types are not objects.
The so-called "objectification" is the ability to organize data and code into complex structures. In JavaScript, only the object type and function type provide objectification capabilities.
No class
Object is the type of object. 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 thing 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. Suddenly there is no "category", and we feel like we have lost our spiritual support and feel that we have no master. It seems that it is not easy to let go of objects and classes and reach the state where "objects have no roots and types are invisible".
So, let’s look at a JavaScript program first:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh to execute]
This JavaScript program initially generated a life object, life. When life was born, it was just a bare object without any properties or methods. In the first life process, it has a body attribute and a say method, which looks like an "egg cell". During its second life, it grew a "tail" and "gills". With the tail and gill attributes, it was obviously a "tadpole". During its third life, its tail and gill attributes disappeared, but it grew "four legs" and "lungs", acquired the legs and lung attributes, and finally became a "frog". If you have a rich imagination, you may be able to turn it into a handsome "prince" and marry a beautiful "princess" or something. However, after reading this program, please think about a question:
Do we definitely need classes?
Do you still remember the fairy tale about "a little tadpole looking for its mother" when you were a child? Maybe just last night, your child happened to fall asleep in this beautiful fairy tale. The cute little tadpole gradually became the same "kind" as its mother during the continuous evolution of its own type, and thus found its mother. The programming philosophy contained in this fairy tale is: the "class" of an object comes from scratch, continues to evolve, and eventually disappears...
"Class" can indeed help us To understand the complex real world, this chaotic real world does need to be classified. But if our thoughts are bound by "category", "category" will become "tired". Imagine, if a living object is assigned a fixed "class" from the beginning, can it still evolve? Can a tadpole turn into a frog? Can you also tell the children the story of a tadpole looking for its mother?
Therefore, there is no "class" in JavaScript. Classes have become invisible and integrated with objects. It is precisely because of letting go of the concept of "class" that JavaScript objects have vitality that other programming languages do not have.
If you begin to feel something deep in your heart at this time, then you have gradually begun to understand the Zen of JavaScript.
The magic of functions
Next, let’s discuss the magic of JavaScript functions.
JavaScript code only has one form: function, and function is the type of function. Maybe other programming languages have code concepts such as procedure or method, but in JavaScript there is only one form of function. When we write a function, we just create an entity of type function. Please look at the following program:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh before executing]
You can see this code after running it What typeof(myfunc) returns is function. We call the above function writing method "definition formula". If we rewrite it into the following "variable formula", it will be easier to understand:
[Ctrl A Full Optional note: If you need to introduce external Js, you need to refresh it before executing]
A variable myfunc is clearly defined here, and its initial value is assigned to a function entity. Therefore, typeof(myfunc) also returns function. In fact, the writing methods of these two functions are equivalent, and except for a few minor differences, their internal implementation is exactly the same. In other words, the JavaScript functions we write are just named variables. The variable type is function, and the value of the variable is the function code body we wrote.
If you are smart, you may immediately ask further: Since functions are just variables, variables can be assigned values arbitrarily and used anywhere?
Let’s take a look at the following code:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh 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 when the function is called for the second time, different output appears.
Okay, let’s change the above code into the first defined function form:
[Ctrl A Select all Note: If you need to introduce external Js needs to be refreshed to execute]
It stands to reason that two functions with exactly the same signature should be illegal in other programming languages. But in JavaScript, this is true. However, after the program was run, a strange phenomenon was discovered: the two calls were only the values output by the last function! Obviously the first function doesn't do anything. Why is this?
It turns out that the JavaScript execution engine does not analyze and execute the program line by line, but analyzes and executes it piece by piece. Moreover, during the analysis and execution of the same program, the defining function statements will be extracted and executed first. After the function definition is executed, other statement codes will be executed in sequence. In other words, 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, both calls execute the last function logic.
If you divide this JavaScript code into two pieces, for example, write them in an html, and use the tag to divide it into two pieces like this:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh it to execute]
At this time, the output comes in order, which also proves that JavaScript is indeed executed piece by piece of.
Defined function statements in a piece of code will be executed first. This seems a bit like the compilation concept of static languages. Therefore, this feature is also called by some people: JavaScript "pre-compilation".
In most cases, we don’t need to get entangled in these details. As long as you remember one thing: the code in JavaScript is also a kind of data, which can also be assigned and modified arbitrarily, and its value is the logic of the code. However, unlike general data, functions can be called and executed.
However, if the JavaScript function is only good at this point, how strange is it compared with C’s function pointer, DELPHI’s method pointer, and C#’s delegate! However, the magic of JavaScript functions is also reflected in two other aspects: first, the function type itself also has the ability to be objectified, and second, the ability to combine functions and objects transcendently.
Wonderful Objects
First let’s talk about the objectification ability of functions.
Any function can dynamically add or remove attributes for it. These attributes can be simple types, objects, or other functions. In other words, functions have all the characteristics of objects, and you can use functions as objects. In fact, a function is an object, but it has one more bracket "()" operator than a normal object. This operator is used to execute the logic of the function. That is, the function itself can still be called, but the general object cannot be called, except that it is exactly the same. Please look at the code below:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh to execute]
In this code, After the Sing function is defined, the author and poem attributes are dynamically added to the Sing function. Setting the author and poem attributes to different authors and poems will display different results when calling Sing(). This example uses a poetic way to let us understand that JavaScript functions are the essence of objects, and also feel the beauty of JavaScript language.
Okay, from the above description, we should understand that the function type things are the same as the object type. This kind of thing is called "object" by us. We can indeed look at these "objects" this way, because they have both "properties" and "methods". But the following code will give us new doubts:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh to execute]
Yes, objects and functions can be accessed and processed like arrays, using property names or method names as subscripts. So, should it be considered an array or an object?
We know that arrays should be regarded as linear data structures. Linear data structures generally have certain rules and are suitable for unified batch iteration operations. They are a bit like waves. Objects are discrete data structures, suitable for describing dispersed and personalized things, a bit like particles. Therefore, we can also ask: Are objects in JavaScript waves or particles?
If there is object quantum theory, then the answer must be: wave-particle duality!
Therefore, functions and objects in JavaScript have the characteristics of both objects and arrays. The array here is called a "dictionary", a collection of name-value pairs that can be arbitrarily expanded. In fact, the internal implementation of object and function is a dictionary structure, but this dictionary structure shows a rich appearance through rigorous and exquisite syntax. Just as quantum mechanics uses particles to explain and deal with problems in some places, it uses waves to explain and deal with problems in other places. You can also freely choose to use objects or arrays to explain and handle problems when needed. As long as you are good at grasping these wonderful features of JavaScript, you can write a lot of concise and powerful code.
Put down the object
Let’s take a look at the transcendent combination of function and object.
In the world of object-oriented programming, the organic combination of data and code constitutes the concept of objects. Since the creation of objects, 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 outside world cannot access the inside of the object without permission. Objects also have a generous side. They provide properties and methods to the outside world and serve others. However, here we have to talk about an interesting issue, which is "the self-awareness of the object".
What? Did you hear that right? Is the subject self-aware?
Perhaps for many programmers, this is indeed the first time they have heard of it. However, please take a look at this in C, C# and Java, self in DELPHI, and me in VB, maybe you will suddenly realize it! Of course, it is possible to just say "nothing more than that".
However, when the object divides the world into internal and external parts, the object's "self" also emerges. "Self-awareness" is the most basic characteristic of life! It is precisely because of the powerful vitality of objects that the programming world is full of infinite vitality and vitality.
But the object’s “self-awareness” not only brings us happiness, but also brings pain and troubles. We attach too many desires to objects, always hoping they can do more. However, the selfishness of objects makes them compete with each other for system resources, the egotism of objects makes objects complex and bloated, and the self-deception of objects often brings lingering errors and exceptions. Why do we have so much pain and trouble?
For this reason, there was a person who thought about it for eighty-one days under the object tree, and finally realized that the pain of life comes from desire, but the root of desire comes from self-awareness. So he put down his "self" and became a Buddha under the object tree. From then on, he began to save all sentient beings and spread the true scriptures. His name is Sakyamuni, and the "JavaScript Sutra" is one of the scriptures he preached.
JavaScript also has this, but this this is different from this in languages such as C, C# or Java. In general programming languages, this is the object itself, but in JavaScript this is not necessarily the case! This may be me, it may be you, it may be him. Anyway, you are in me, and I am in you. Therefore, you cannot use the original "self" to understand the meaning of this in JavaScript. To do this, we must first let go of the "self" of the original object.
Let’s take a look at the following code:
[Ctrl A to select all Note: If you need to introduce external Js, you need to refresh to execute]
As you can see from the above code, the same function can be called from different angles, and this is not necessarily the object to which the function itself belongs. This is just a concept when combining any object with a function element. This combination is more flexible than the default combination of general object languages, and appears more detached and free.
In a JavaScript function, you can only regard this as the "this" object currently being served. This is a special built-in parameter. According to this parameter, you can access the properties and methods of "this" object, but you cannot assign a value to this parameter. In general object languages, this in the method body code can be omitted, and members are "self" first by default. But JavaScript is different. Since there is no "self", when accessing "this" object, this cannot be omitted!
JavaScript provides a variety of forms and means of passing this parameter. Among them, forms such as BillGates.WhoAmI() and SteveJobs.WhoAmI() are the most formal forms of passing this parameter. At this time, this It is the object itself that the function belongs to. In most cases, we rarely use the form of invocation that borrows flowers from immortals and Buddhas. But as long as we understand that the "self" of JavaScript is different from the "self" of other programming languages, it is a "self" that has been let go. This is the unique world view of JavaScript.
Object Sketch
We have talked about many topics, but there is a very basic question that we forgot to discuss, that is: how to create objects?
In the previous example, we have already involved the creation of objects. We use a form called JavaScript Object Notation (abbreviated JSON), which is translated into Chinese as "JavaScript Object Notation".
JSON provides a very simple way to create 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 properties and methods:
var speaker = {text: "Hello World", say: function(){alert(this.text)}};
Create a more complex object, nesting other objects, arrays of objects, etc.:
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 format of JSON is to use braces "{}" A list of items enclosed by ",", each item is separated by a comma ",", and the item is the attribute name and attribute value separated by a colon ":". This is a typical dictionary representation, and it once again shows that objects in JavaScript are dictionary structures. No matter how complex the object is, it can be created and assigned with a JSON code.
In fact, JSON is the best serialization form of JavaScript objects. It is more concise and space-saving than XML. The object can be used as a string in the form of JSON to freely transmit and exchange information between networks. When you need to turn this JSON string into a JavaScript object, you only need to use the eval function, a powerful digital conversion engine, to get a JavaScript memory object immediately. It is precisely because of the simple and simple natural beauty of JSON that she becomes a dazzling star on the AJAX stage.
JavaScript is like this, expressing seemingly complex object-oriented things in an extremely concise form. Take off your partner’s flashy and heavy makeup, and give your partner a clear-eyed look!
Constructing objects
Okay, let’s discuss another method of creating objects.
In addition to JSON, in JavaScript we can use the new operator combined with a function to create objects. For example:
function MyFunc() {}; //Define an empty function
var anObj = new MyFunc(); //Use the new operator and the MyFun function to create an object
This way of creating objects in JavaScript is really interesting. How to understand this way of writing?
In fact, the above code can be rewritten into this equivalent form:
function MyFunc(){};
var anObj = {}; //Create an object
MyFunc. call(anObj); //Call the MyFunc function using the anObj object as this pointer
We can understand this way, JavaScript first creates an object using the new operator, and then uses this object as this parameter to call the following function . 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 see a familiar figure again. Isn't this how C and C# create objects? It turns out that all roads lead to Lingshan, and they lead to the same destination!
When you see this, you may think, why can’t we use this MyFunc as a constructor? Congratulations, you got it right! JavaScript thinks so too! Please look at the code below:
Copy 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) ;}; //Define a SayHello method for this object.
5 };
6
7 function Employee(name, salary) //Sub constructor
8 {
9 Person.call(this, name); Parent constructor
10 this.salary = salary; //Set a salary attribute of this
11 this.ShowMeTheMoney = function() {alert(this.name " $" this.salary);}; // Add ShowMeTheMoney method.
12 }; 1234); //Use the Empolyee constructor to create a SteveJobs object
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 functions can not only be used as constructors, but can also take parameters, and can also add members and methods to objects. In line 9, the Employee constructor calls the Person constructor using the this it receives as a parameter, which is equivalent to calling the base class constructor. Lines 21 and 22 also indicate the following: BillGates is constructed from Person, and SteveJobs is constructed from Employee. The built-in constructor property of the object also specifies the specific function used to construct the object!
In fact, if you are willing to think of a function as a "class", she is a "class" because she originally has the characteristics of a "class". Isn't it? The sons she gave birth to all have the same characteristics, and the constructor also has the same name as the class!
Current page 1/2 12Read the full text on the next page