http://www.cnblogs.com/leadzen/archive/2008/02/25/1073404.html Classic

Introduction

Programming the world exist only two basic elements, one is data, a code. Programming world is in the data and code in a web of tangled displays unlimited vigor and vitality.

Data is inherently quiet, with a total want to maintain their inherent qualities; and code are naturally lively, with a total want to change the world.

You see, the relationship between the data source of energy and material relations between the surprisingly similar. Data also have inertia, if there is no code to exert external force, she always maintain its original state. The code is like energy, he's the sole purpose of existence is to try to change the original state data. Code change data at the same time, also because of the resistance data and in turn affect or change the code the original trend. Even in some cases, data can be transformed into code, and the code but there is likely to be transformed into data, may also exist a similar form of E = MC2 equation does the digital conversion. However, that is, in the data and code that the contradictions between such a unified operation, always reflect the law of the computer world, these laws is exactly what we prepared logic.

However, because different programmers have different world view, these data and the code will look different. Thus, different view of the world's programmers to use their own methodology, to promote the evolution of the programming world and development.

As we all know, today's most popular programming idea is the idea of object-oriented programming. Why is the idea of object-oriented programming quickly swept the world? Since the first idea of object-oriented data and code put into the continuum, and the concept of a simple object presented to the programmer. This all of a sudden those who will be the original algorithm and subroutine clutter, as well as entangling complex data structure, divided into clear and orderly structure of the object, thereby clarifying the data and code in our hearts that knot-like乱麻Mission. We can have a more clear thinking, high up on another idea to explore a more vast programming world.

Legend taught at弘忍End "object真经" after day, he had his disciples of the public said: "has just been finished, presumably Seoul sentiment should be, please look at their respective偈子个Writing." Disciples are to be神秀big U.S. public think the most savvy senior, his偈子wrote: "who are the object tree, such as type of heart as prescribed.朝朝ground dust, Do not can the dust alight!."此偈an immediate sensation caused师兄弟们, everyone says that written wonderful. Monk Huineng only look after the flame and gently sighed and picked at the wall wrote: "This object has no roots, the type is also invisible. Originally, no one objects, where can the dust alight?." Then shook his head, left. The U.S. saw Huineng偈子say: "What is written in a Mess of the ah, can not read."弘忍master read poetry神秀also nodded his head mechanic praise poems Huineng look after the mechanic shook his head in silence. On the same day at night, has quietly put Huineng弘忍called its own Buddhist temple, the software will treasure for many years to teach in真经him, then let him take advantage of the moonlight night to escape ...

Later, the master trust Huineng really high hopes, in the South created a Zen another broad sky. Huineng was taken away and the software there are a真经are "JavaScript真经"!

Simple regression

To understand JavaScript, you must first put aside the concept of objects and classes and return to the primitive data and code. As mentioned above, programming the world's only data and code are two basic elements, and these two elements also have a tangled relationship. JavaScript is to put data and code are simplified to the most primitive level.

The data in JavaScript is very simple. Easy data only undefined, null, boolean, number and string these five, and complex data, only one, namely, object. This is like Chinese classical simple materialist thought, put the most basic elements of the world classified as金木水火土, and other complex substances by these five basic elements.

JavaScript code is only manifested in a form that function.

Note: The above words are all lowercase, and not to Number, String, Object, Function built-in functions, such as JavaScript confused. Need to know, JavaScript language is case-sensitive you!

Any one of JavaScript's logo, constants, variables and parameters are only unfined, null, bool, number, string, object and function types, typeof also showed that the type of return value. In addition there are no other types of.

First to give you easy data types.

undefined: on behalf of all unknown things, nothing, can not imagine the code it will not be able to handle the go.
Note: typeof (undefined) return is undefined.
Undefined can be assigned to any variable or property, but this does not mean that the removal of the variable, it will therefore have one more property.

null: there is then a concept, but nothing. None appear to have, there is also no. Although hard to imagine, but can be used to deal with the code.
Note: typeof (null) return object, but null is not the object, with a null value of the variable is not object.

boolean: yes that is, non-non, there is no doubt. On the right, it would be wrong, absolutely clear. Code can be deal with, but also can control the code flow.

number: linear things, size, and the order is clear, many without chaos. Code to facilitate batch processing, but also control code and the iterative cycle.
Note: typeof (NaN) and typeof (Infinity) are back number.
NaN participate in any numerical calculation of the structure are NaN, and NaN! = NaN.
Infinity / Infinity = NaN.

string: the rational thing for human beings, not machines signal. Man-machine communication, code accordingly to understand people's intentions and so on, have been relied.

Simple types are not objects, JavaScript objects do not confer the ability of these simple types. Directly be given the type of easy money often identifiers, variables and parameters is not an object.

The so-called "object oriented", that is, data and code can be organized into complex structures. JavaScript, only the type of object type and function to provide the target capacity.

No category

object is the type of object. Medium in JavaScript, no matter how complex data and code can be organized into object form of the object.

However, JavaScript has no "type" concept!

For many object-oriented programmers, this is probably the most difficult to understand JavaScript place. Ah yes, almost any object-oriented book stresses, the first want to say is the "type" concept, this is the pillar of object-oriented. This sudden lack of a "category", we did not like all of a sudden spiritual pillars are六神无主. It appears that objects and classes to put aside to achieve "the target of this non-root, type also invisible" realm is indeed not be easy ah.

In this way, we first take a look at JavaScript for some procedures:
var life = ();
for (life.age = 1; life.age <= 3; life.age + +)
(
switch (life.age)
(
case 1: life.body = "egg";
life.say = function () (alert (this.age + this.body));
break;
case 2: life.tail = "tail";
life.gill = "gills";
life.body = "tadpole";
life.say = function () (alert (this.age + this.body +"-"+ this.tail +","+ this.gill));
break;
case 3: delete life.tail;
delete life.gill;
life.legs = "four legs";
life.lung = "lung";
life.body = "frog";
life.say = function () (alert (this.age + this.body +"-"+ this.legs +","+ this.lung));
break;
);
life.say ();
);

JavaScript start this procedure resulted in a one object of life life, life was born just a naked object, there is no property and methods. At first the life course, there is a property of physical body, and have a say methods, appears to be an "egg." Life in the second process, it sprouted a "tail" and "gills", with tail and gill property, it is clear that it is a "tadpole." At the third time in the life course, and its tail and gill property disappeared, but grow the "four legs" and "lungs", with the legs and lung property, which eventually turned into a "frog." If you, your imagination, then perhaps it will turn into handsome "Prince", married a beautiful "princess" or something. However, after watching this program, please consider you a question:

We must need to type it?

Still remember childhood that "little tadpole looking for Mother," the fairy tale吗? Yesterday may be late, your child happens to be in this beautiful fairy tale of the right to enter dreamland. Cute small tadpole that is, at its own type of continuous evolution, has gradually become the mother and the same "category" in order to find its own mother. This fairy tale contains programming philosophy is this: the object "category" from scratch are also evolving, they finally disappear into the ...

"Class" can indeed help us to understand the complexity of the real world, this confusion of the real world is indeed to be classified. However, if the U.S. thought was, "category" locking, and "Class" will become "tired." Imagine, if a life that began when the object has been provided for a fixed "category", then it can evolution吗? Frog tadpoles can become吗? Can also give the children a small tadpole-speaking mother to find the story?

Therefore, JavaScript does not "category", category has been based on the intangible, and object integration. It was put aside because of the "type" concept, JavaScript object only other programming languages do not have the vitality.

If, when you start some deep insights, then you have gradually begin to understand the Zen of JavaScript.

Function of the magic

Next, we discuss the magic of your JavaScript function.

JavaScript code can only function as a form, function is the function type. There may be other programming language code such as procedure or method, but only function in JavaScript form. When we write a function of time, just set up a function only types of entities. See the following procedures:
function myfunc ()
(
alert ( "hello");
);

alert (typeof (myfunc));

This code can be seen running after the typeof (myfunc) are the return function. More than a function of writing we call "the definition of" type of, if we be rewritten into the following "variable" type of, even easier to understand:
var myfunc = function ()
(
alert ( "hello");
);

alert (typeof (myfunc));

Here a clear definition of a variable myfunc, of its initial value is given a function of the entity. Therefore, typeof (myfunc) is the return function. In fact, the wording of these two functions are equivalent, except that the nuances of its internal implementation is identical. In other words, we write these JavaScript function is only an order of the names of variables only, the variable type is the function, the variable's value is that we prepare a function of the code body.

Clever you may immediately be further asked: Now that function is variable, then the variables can be arbitrarily assigned and used in place of arbitrary Hello?

We take a look at the following code:
var myfunc = function ()
(
alert ( "hello");
);
myfunc (); / / first call myfunc, output hello

myfunc = function ()
(
alert ( "yeah");
);
myfunc (); / / second call myfunc, the output yeah

The results of running this process tell us: the answer is yes! At first after the function call, function variables has been given a new function code body, making the second call to this function when a different output.

Well, we again put the above code into a first-style function definition of the form:
function myfunc ()
(
alert ( "hello");
);
myfunc (); / / here call myfunc, rather than output yeah hello

function myfunc ()
(
alert ( "yeah");
);
myfunc (); / / here call myfunc, the output of course yeah

Reason, two identical Signature function, in other programming languages should be illegal. However, in JavaScript, this is true. However, the program runs after they found a strange phenomenon: twice to call that function only in the final output value! Obviously the first function does not play any role. This is Why?

The original, JavaScript execution engine is not a line by line analysis and implementation of procedures, but for some period of analysis of the implementation. Moreover, in the same paragraph, the analysis of the implementation procedures, the definition of a function of statement type will be extracted to give priority to implementing. After the implementation of function definition, before any other statement the order code. In other words, at first before calling myfunc, the first statement the definition of function code logic, has been the second statement covers the function definition. Therefore, both the implementation of the final call is a function of logic.

If you put the JavaScript code is divided into two sections, for example, they write in a html, and use <script/> this tag will be divided into two:
<script>
function myfunc ()
(
alert ( "hello");
);
myfunc (); / / here call myfunc, output hello
</ script>

<script>
function myfunc ()
(
alert ( "yeah");
);
myfunc (); / / here call myfunc, output yeah
</ script>

At this time, the output is in accordance with their respective order, and it proves that indeed is a JavaScript implementation of the paragraph.

The definition of a section of code-type function would give priority to the implementation of statements, it seems a bit like the concept of a static language compiler. Therefore, this feature has also been some people referred to as: JavaScript's "pre-compiled."

In most cases, we do not need to struggle these details. As long as you bear in mind: JavaScript is also a kind of code in the data, the same can be arbitrary assignment and modification, and its value is the code logic. However, with the general data are different, function calls can be implemented.

However, if the JavaScript function only Daoxing this point, it is with C + + the function pointer, DELPHI method pointer, C # compared to the commission, but also what he wonder why! However, JavaScript function of magic is also reflected in the other two aspects: First, the type of function function object itself has the capacity, and the other is the target object function function with the combination of transcendent ability.

Fantastic Object

Say for the first function of the capacity of the object.

Any one function can be dynamically added or for the removal of property, the property can be a simple type, can be objects, can also be other functions. In other words, the function has all the characteristics of the object, you can put to use when the object function. In fact, the function is the object, but the object of many than a pair of brackets "()" operator, the operator used to perform logic functions. Namely, the function itself can also be called, the general object can not be called, in addition to exactly the same. See the following code:
function Sing ()
(
with (arguments.callee)
alert (author + ":" + poem);
);
Sing.author = "Li Bai";
Sing.poem = "Han Chin to month, streaming video lighting Princess. Jade Guan Road on one, do not go to the End of the World";
Sing ();
Sing.author = "Lee war";
Sing.poem = "sunrise Han days before moonset Yinshan. Pipa resentment daughter has been singing three thousand years";
Sing ();

At this code, Sing function is defined, the given function dynamically Sing increased property author and poem. The author and the poem set to a different property of authors and poems, in the call Sing () when we can show different results. This example in a poetic way, let us understand the JavaScript function that is the essence of objects, but also feel the beauty of JavaScript language.

Well, the above described, we should count to understand the function and the types of things are the same object type of thing, this kind of thing was what we call "object." Indeed, we can go look at these "target", because they both "property" also has "methods" do. However, the following code also will enable us to generate a new doubts:
var anObject = (); / / an object
anObject.aProperty = "Property of object"; / / object of a property
anObject.aMethod = function () (alert ( "Method of object")); / / object as a means of
/ / Main look below:
alert (anObject [ "aProperty"]); / / can be the target when the array to the property name as a subscript to access property
anObject [ "aMethod "](); / / can be the target when the array name as a method to call methods subscript
for (var s in anObject) / / traverse the object of all property and iterative methods of treatment
alert (s + "is a" + typeof (anObject [s]));

For the same type of object function is the same:
var aFunction = function () (); / / a function
aFunction.aProperty = "Property of function"; / / function of a property
aFunction.aMethod = function () (alert ( "Method of function")); / / function as a means of
/ / Main look below:
alert (aFunction [ "aProperty"]); / / can be to function as an array subscript as the property name to access the property
aFunction [ "aMethod "](); / / can function as an array to method name as a subscript to call the method
for (var s in aFunction) / / traverse all property functions and methods of treatment iterative
alert (s + "is a" + typeof (aFunction [s]));

Yes, object and function can be the same as the array, using the property name or method name as a subscript to access and deal with. Then, in the end it should be regarded as an array, or count objects?

We know that the array data structure should be regarded as linear, linear data structures in general must have the rules suitable to carry out a unified iterative batch operation, a bit like a wave. And targeted at discrete data structure, suitable to describe decentralized and personalized things, a bit like a particle. Therefore, we could ask: JavaScript's objects are waves or particles in the end?

If objects exist in quantum theory, the answer must be: wave-particle duality!

Therefore, JavaScript functions and objects in both the characteristics of the object also has an array of features. The array is called "dictionary", a kind of stretching can be the name of the value of a collection of children. In fact, object and function is an implementation of the internal dictionary structure, but the structure of this dictionary is an elaborate and sophisticated grammar show a rich appearance. As quantum mechanics particles used in some places to explain and deal with questions, while in other places they have made use of waves to explain and deal with questions. You can also, when necessary, to free choice of the object or an array to explain and deal with questions. Mastery of JavaScript as long as these wonderful features, you can produce a lot of simple and powerful code to.

Put object

Let us look at the transcendent function and object combination of now.

Object-oriented programming in the world, data and code constitutes the organic integration of the concept of object. Since the object, programming the world is divided into two parts, one is the object of the world, and one is outside the object world. Object innate selfish side, the outside world without a permit are not accessible within the object. Target also has generous side, which provide properties and methods, but also the service of others. However, here we want to talk about an interesting question, that is, "the object of self-awareness."

What? Heard of mistake, right? Object has self-consciousness?

Possible for many programmers, it is first heard. However, please take a look at C + +, C # and Java, this, DELPHI's self, have VB of me, perhaps you will suddenly! Of course, it may only be "much better than" just.

However, at the object inside and outside the world is divided into two parts at the same time, the object "self" is the resulting. "Self-consciousness" are the most basic features of life! It is precisely because the object of such great vitality that makes programming world is full of infinite vigor and vitality.

But the object of "self-consciousness" brought us happy at the same time also brought the pain and trouble. We give too much desire for the object given a total of hope that they can do more things. However, the object makes them selfish competition for system resources with each other, the object so that objects become self-complicated and bloated, self-deception is often the object brought about by lingering errors and exceptions. Why is there so much of our pain and trouble it?

To this end, there is a person, in the object tree, think of the whole九九八十一days, and finally realize his life suffering from the desire, but their desire to study the root causes are from the self-consciousness. So he put aside the "self" in the object tree has become a Buddha, then he began to Purdue creatures, dissemination真经. His name is called迦摩尼release, and "JavaScript真经" It is his Biography book by one.

JavaScript also has this, but that this is with C + +, C # or Java and other languages of this different. General programming language this is the object itself, and JavaScript are not necessarily of this! this may be me, or it may be you could be him, anyway, there you are me, you have me, which should not use the original "self" to understand the meaning of JavaScript that this has been. To this end, we must first put aside the original object that the "self."

We look at the following code:
function WhoAmI () / / define a function whoami
(
alert ( "I'm" + this.name + "of" + typeof (this));
);

WhoAmI (); / / At this point it is this current period of global object code, in your browser is the window object, its name property to an empty string. Output: I'm of object

var BillGates = (name: "Bill Gates");
BillGates.WhoAmI = WhoAmI; / / will function as whoami BillGates method.
BillGates.WhoAmI (); / / At this point of this is BillGates. Output: I'm Bill Gates of object

var SteveJobs = (name: "Steve Jobs");
SteveJobs.WhoAmI = WhoAmI; / / will function as whoami SteveJobs method.
SteveJobs.WhoAmI (); / / At this point of this is SteveJobs. Output: I'm Steve Jobs of object

WhoAmI.call (BillGates); / / directly to BillGates as this, call WhoAmI. Output: I'm Bill Gates of object
WhoAmI.call (SteveJobs); / / directly to the SteveJobs as this, call WhoAmI. Output: I'm Steve Jobs of object

BillGates.WhoAmI.call (SteveJobs); / / will SteveJobs as this, but the whoami call BillGates Ways. Output: I'm Steve Jobs of object
SteveJobs.WhoAmI.call (BillGates); / / will BillGates as this, but the whoami call SteveJobs Ways. Output: I'm Bill Gates of object

WhoAmI.WhoAmI = WhoAmI; / / whoami function will be set to its own methods.
WhoAmI.name = "WhoAmI";
WhoAmI.WhoAmI (); / / At this point of this function are whoami own. Output: I'm WhoAmI of function

((name: "nobody", WhoAmI: WhoAmI)). WhoAmI (); / / temporary to create an anonymous object and set the property after the method call whoami. Output: I'm nobody of object

From the above code can be seen that the same function from different angles to call, this is not necessarily a function of the object of their own. this only in the arbitrary function objects and combine elements of a concept, is a combination of general objects than the default language combination more flexible, even more aloof and free and easy.

In the JavaScript function, you can only put this as a present to serve "this" object. this is a special built-in parameters, according to this the parameters, you can visit to "this" object's properties and methods, but it should not give this parameter assignment. In general the target language, methods, precursors of this code can be omitted, the default is first and foremost members of their "own". However, JavaScript is different, because there is no "self", when the visit to "this" object, this can not be omitted!

JavaScript provides the transmission of this parameter in various forms and means, which, like BillGates.WhoAmI () and SteveJobs.WhoAmI () This form is to pass this parameter the most formal form, at this time this is the function object itself belongs . While the majority of cases, we rarely go borrow the use of those flower forms仙佛call. But we need to understand the JavaScript of the "self" and other programming languages the "self" is different, this is a put down of "self", which is unique worldview JavaScript.

Object sketch

Much has been said a lot of topics, but there is a very basic question we forgot to discuss, and that is: How to set up the object?

In the previous example, we have involved the establishment of object. We use a called JavaScript Object Notation (abbreviation JSON) format, translated into English is "JavaScript Object Notation."

JSON to create object to provide a very easy method. For example,
Create a property of any object:
var o = ();

Create an object and set property and the initial value:
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, nested arrays and objects to other objects, such as:
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 form of JSON is to use large, including "()" including its list of items together, between each item and use a comma "," separated, while the project is to use a colon ":"-separated property name and property value. Dictionary This is a typical form of express, but also once again shows the JavaScript's object dictionary structure. No matter how complex objects can be a JSON code to create and assign.

In fact, JSON is JavaScript Object Serialization best form, it is also more concise than XML and more space. JSON objects can be used as a form of string networks at transmission and exchange information freely. And when necessary will be the JSON string into a JavaScript object, only need to use the eval function of this powerful digital conversion engine, on the immediate memory can be provided with a JavaScript object. It is precisely because of this simple JSON simple natural beauty, she makes the AJAX arena璀璨夺目become a star.

JavaScript is one such, who appears to put the complexity of object-oriented things, with its simple form of expression. To unload the object of heavy makeup vanity, but also the object of a clear prospect of a solution!

Structure object

Well, take us to discuss the creation of the object to another method.

In addition to JSON, in JavaScript, we can use the new operator of the form combined with a function to create objects. For example:
function MyFunc () (); / / define an empty function
var anObj = new MyFunc (); / / use the new operator, with MyFun function, on the creation of an object

JavaScript to create objects of this can be really interesting to understand how such a manner?

In fact, you can put the above code rewritten into the equivalent of such forms:
function MyFunc (){};
var anObj = (); / / create an object
MyFunc.call (anObj); / / will anObj object as this function pointer to call myFunc

We can interpret it this way, JavaScript first new operator to create an object, this object will be followed by this parameter as a function of call behind. In fact, JavaScript is done within, and any function can be called such! However, "anObj = new MyFunc ()" in this form, we can also see a familiar figure, C + + and C # do not create the object is it? It turned out that All roads lead to Lingshan, achieving the same ah!

Jun seen here may think, why should we not put this myFunc it as a constructor? Congratulations, the correct answers! JavaScript is also a thought! See the following code:
1 function Person (name) / / constructor with parameters
2 (
3 this.name = name; / / will give the parameter values assigned to this object property
4 this.SayHello = function () (alert ( "Hello, I'm" + this.name);); / / give this object to define a method SayHello.
5);
6
7 function Employee (name, salary) / / sub-constructor
8 (
9 Person.call (this, name); / / will this pass the parent constructor
10 this.salary = salary; / / set up a salary of this property
11 this.ShowMeTheMoney = function () (alert (this.name + "$" + this.salary);); / / add ShowMeTheMoney Ways.
12);
13
14 var BillGates = new Person ( "Bill Gates"); / / constructor used to create Person object BillGates
15 var SteveJobs = new Employee ( "Steve Jobs", 1234); / / constructor used to create Empolyee object SteveJobs
16
17 BillGates.SayHello (); / / show: I'm Bill Gates
18 SteveJobs.SayHello (); / / show: I'm Steve Jobs
19 SteveJobs.ShowMeTheMoney (); / / show: Steve Jobs $ 1234
20
21 alert (BillGates.constructor == Person); / / show: true
22 alert (SteveJobs.constructor == Employee); / / show: true
23
24 alert (BillGates.SayHello == SteveJobs.SayHello); / / show: false

This code shows that not only can function as a constructor, but also can take parameters, can also add members and methods of the object. One of the first 9 lines, Employee constructor will receive its own as a parameter of this call Person constructor, which is equivalent to call the base class's constructor. 21,22 also show that the first line of such a meaning: BillGates are constructed by the Person, and SteveJobs are constructed by the Employee. Built-in object constructor property is also specified in the object structure used in the specific function!

In fact, if you are willing to function as a "category", she is the "category", because she already has "Class" of those characteristics. Is not it? Give birth to her son all have the same characteristics, but also with the type constructor of the same name it!

Yet it must be noted, the operation of this object constructor to create an object out of each, not only with members of their respective data, but also has its own method of data. In other words, the method code body (embodiment of the logic function of data) at each object in a copy of all existence. Even though a copy of each of the logic of the code are the same, but the objects were indeed a code to preserve their own body. Example on the last sentence of the facts shows, this also explains the JavaScript function is the object of the concept.

The same type of object has a method of their code is a waste. In a traditional programming language, the method does not function as JavaScript object as a concept. Even if there is also as function pointer, method pointer, or as changes in the form of commission, but its essence is to invoke the same code. The target language in general difficult to come across such cases.

However, JavaScript language has great flexibility. We can only approach the definition of a function body, and this object structure to use the only function of the object as part of its methods, will be able to share the method logic. For example:
function SayHello () / / first define a function code SayHello
(
alert ( "Hello, I'm" + this.name);
);

function Person (name) / / constructor with parameters
(
this.name = name; / / will give the parameter values assigned to this object property
this.SayHello = SayHello; / / give this object SayHello Ways SayHello that assignment for the previous code.
);

var BillGates = new Person ( "Bill Gates"); / / create object BillGates
var SteveJobs = new Person ( "Steve Jobs"); / / create object SteveJobs

alert (BillGates.SayHello == SteveJobs.SayHello); / / show: true

Among them, the last line of the output results show that the two objects is indeed a shared function objects. Although this process has reached a method of sharing the purpose of the code, but not very elegant. Since the definition SayHello methods do not reflect its relationship with the Person class. "Elegant," the term used to describe the code, do not know who are put forward. However, the word reflects the programmers code from the pursuit of the correct, efficient, reliable and easy to read on a reciprocal basis, toward the pursuit of beautiful code realm of feeling and artistic level of development, the program also Any additional romantic life.

Clearly, JavaScript morning thought of this question, her designers to provide a fun concept prototype.

Watch the early prototype

prototype derived from the French, the software sector standards translated as "prototype", the representative of the initial shape of things, but also contain models and model significance. JavaScript concept of prototype appropriately reflects the content of the word, we should not be interpreted as a C + + pre-statement of the kind of prototype concept.

JavaScript all the function types of objects have a prototype property. The prototype property itself is a type of object, so we can also give the prototype object to add arbitrary attributes and methods. Now that prototype object are the "prototype", then the function should be constructed out of objects will have this "prototype" features. In fact, in the constructor's prototype on the definition of all properties and methods, can be constructed through the object of direct visits and calls. Can also say, prototype object to provide a group of similar properties and methods of sharing mechanisms.

Let us take a look the following code:
function Person (name)
(
this.name = name; / / set object properties, each object a property of their respective data
);

Person.prototype.SayHello = function () / / function prototype give Person Ways SayHello add.
(
alert ( "Hello, I'm" + this.name);
)

var BillGates = new Person ( "Bill Gates"); / / create object BillGates
var SteveJobs = new Person ( "Steve Jobs"); / / create object SteveJobs

BillGates.SayHello (); / / object through direct calls to BillGates Ways SayHello
SteveJobs.SayHello (); / / through a direct call to the object SteveJobs Ways SayHello

alert (BillGates.SayHello == SteveJobs.SayHello); / / because both objects are shared prototype of SayHello, so show: true

Program showed that the prototype constructor method on the definition of the object could indeed be a direct call through to, and code are shared. Clearly, the methods set to prototype formulation seems more elegant, even though the form of calls has not changed, but it reflects on the logic of methods and types of relations, the relative in front of the wording easier to understand and organize code.

Then, for multi-level type constructor situation be?

We will look at the following code:
1 function Person (name) / / base class constructor
2 (
3 this.name = name;
4);
5
6 Person.prototype.SayHello = function () / / to base class constructor's prototype add method
7 (
8 alert ( "Hello, I'm" + this.name);
9);
10
11 function Employee (name, salary) / / subclass constructor
12 (
13 Person.call (this, name); / / Call base class constructor
14 this.salary = salary;
15);
16
17 Employee.prototype = new Person (); / / build a base class object as a subclass prototype prototype here is very interesting
18
19 Employee.prototype.ShowMeTheMoney = function () / / to subclass constructor prototype Tim Add method
20 (
21 alert (this.name + "$" + this.salary);
22);
23
24 var BillGates = new Person ( "Bill Gates"); / / create a base class of the Person object BillGates
25 var SteveJobs = new Employee ( "Steve Jobs", 1234); / / create a subclass of the Employee object SteveJobs
26
27 BillGates.SayHello (); / / through a direct call to the prototype object of the Ways
28 SteveJobs.SayHello (); / / through the sub-class object directly call the base class method prototype concern!
29 SteveJobs.ShowMeTheMoney (); / / the object directly through the sub-class called subclass prototype method
30
31 alert (BillGates.SayHello == SteveJobs.SayHello); / / show: true, show that the prototype approach is shared

Section 17 of this code line, construction of a base class object and set the subclass constructor prototype, this is very interesting. The purpose of this is that for the first 28 lines, through the sub-class object can also directly call the base class method prototype. Why is it so?

In fact, in the JavaScript in, prototype objects can not only share their wealth, and the prototype have寻根问祖nature, allowing the legacy of our ancestors can be passed from generation to generation. When reading from an object where the property or call the method, the object itself if there is no such property or method, it will go its own associated prototype object, where looking for; prototype if not, will go their associated prototype, where the older generation prototype search until you find or trace the process until the end.

JavaScript at the internal, object properties and methods of retrospective mechanism is through the so-called prototype chain to achieve. When using new operator object structure will also be the object constructor prototype is assigned to the newly created object, become the targets of the built-in object prototype. Built a prototype object is the external object is not visible, although some browsers (such as Firefox) can allow us to access the built prototype, but do not propose to do so. Built a prototype object is itself the object, also has its own associated prototype object, thus forming the so-called prototype chain.

At the end of the prototype chain is the Object constructor prototype property that point to a prototype object. The prototype objects are all objects of the oldest ancestor, the ancestor, such as the toString implementation, such as all objects have a natural on the way. Other built-in constructor function, such as Function, Boolean, String, Date and RegExp, such as the prototype are inherited from the ancestors, but also defined their own properties and methods, so their children and grandchildren on the performance of their respective clans those characteristics.

Is not that what "inheritance"吗? Yes, this is the "inheritance", are unique to JavaScript "prototype inheritance."

"Prototype inheritance" is a kind and severe. Prototype object to their property and means to contribute selflessly to the children to use, but also do not force children to be complied with, permit a number of naughty children by their own interests and hobbies to act independently. From this point of view, the prototype object is a kind-hearted mother. However, any one child can go its own way, but it should not move the prototype object existing property, because it may affect the interests of other children. From this point of view, the prototype object also as a strict father. We take a look at the following code can be understood that way:
function Person (name)
(
this.name = name;
);

Person.prototype.company = "Microsoft"; / / prototype property

Person.prototype.SayHello = function () / / prototype of the Ways
(
alert ( "Hello, I'm" + this.name + "of" + this.company);
);

var BillGates = new Person ( "Bill Gates");
BillGates.SayHello (); / / because of inherited prototype things honest output: Hello, I'm Bill Gates

var SteveJobs = new Person ( "Steve Jobs");
SteveJobs.company = "Apple"; / / set up your own company property to cover up the prototype property of the company
SteveJobs.SayHello = function () / / implementation methods SayHello their own to cover up the prototype SayHello Ways
(
alert ( "Hi," + this.name + "like" + this.company + ", ha ha ha");
);

SteveJobs.SayHello (); / / are covered by their own properties and methods, output: Hi, Steve Jobs like Apple, ha ha ha

BillGates.SayHello (); / / SteveJobs coverage does not affect the prototype object, BillGates old way or the output

Object prototype object can be hidden to those properties and methods, a constructor prototype can also cover up the upper object constructor prototype objects and methods of the existing property. Conceal the fact that only objects at them to create a new property and method, but these attributes and methods of those objects with the prototype of the same name only. JavaScript is used to cover up this simple mechanism to achieve the object of "multi-state" nature of the target language with a static virtual function and overloading (override) happens to coincide with the concept.

However, more than the static object language are magic, we can always give the prototype to add a new dynamic object properties and methods, which dynamically extend the base class of functional properties. This static object language is very difficult to imagine. We look at the following code:
function Person (name)
(
this.name = name;
);

Person.prototype.SayHello = function () / / set up the definition of the object before the Ways
(
alert ( "Hello, I'm" + this.name);
);

var BillGates = new Person ( "Bill Gates"); / / set up object

BillGates.SayHello ();

Person.prototype.Retire = function () / / set up the object after the dynamic expansion of the prototype approach
(
alert ( "Poor" + this.name + ", bye bye!");
);

BillGates.Retire (); / / dynamic expansion method may be previously set up the object of an immediate call

Thor Kanami Buddha, the prototype inheritance could play out there is this kind of magic!

Prototype expansion

Must have the savvy high-jun, may be you would think: If those in the JavaScript built-in such as Object and Function of the prototype function, such as add on some new methods and attributes, are not able to extend the JavaScript functions?

Well, Congratulations, you have been!

At the rapid development of AJAX technology today, many successful AJAX runtime JavaScript projects are large-scale expansion of the built-in functions of the prototype function. Such as Microsoft's ASP.NET AJAX, given these built-in functions and prototype added many new features, thus increasing the JavaScript function.

We look at a section of code from MicrosoftAjax.debug.js:

String.prototype.trim = function String $ trim () (
if (arguments.length! == 0) throw Error.parameterCount ();
return this.replace (/ ^ \ s + | \ s + $ / g,'');
)

This code is to give the built-String Function prototype Ways to expand a trim, so all of the String class object has a trim of the Ways. With this expansion, the next two paragraphs to remove the blank string, it will no longer need to deal with separately, because any string that has been the expansion of functions, as long as the call can be really easy.

Of course, few people go almost give Object to add the prototype method, because it will affect all objects, unless you at the architecture in this way are all the objects are indeed necessary.

Two years ago, Microsoft AJAX Library in the early stages of design, using a kind of known as the "closure" (closure) technology to simulate the "Class." Roughly model the following:
function Person (firstName, lastName, age)
(
/ / Private variables:
var _firstName = firstName;
var _lastName = lastName;

/ / Public variables:
this.age = age;

/ / Methods:
this.getName = function ()
(
return (firstName + "" + lastName);
);
this.SayHello = function ()
(
alert ( "Hello, I'm" + firstName + "" + lastName);
);
);

var BillGates = new Person ( "Bill", "Gates", 53);
var SteveJobs = new Person ( "Steve", "Jobs", 53);

BillGates.SayHello ();
SteveJobs.SayHello ();
alert (BillGates.getName () + "" + BillGates.age);
alert (BillGates.firstName); / / here should not have access to private variables

Clearly, this model describes the particular type of C # language as a description of the form, in a constructor in the definition followed by private members, public property and available methods, why it is very elegant. Especially the "closure" mechanism can be simulated on the private members of the protection mechanisms do very beautiful.

The so-called "closure" is defined in the constructor body other function as a way to target function, and the object function in turn quoted the outer body of the outer function temporary variables. This makes as long as the target audience at the survival period will always be able to maintain its methods, will be able to indirectly maintain the original constructor body was used in the provisional variable value. Begin the construction even though the function call has ended, the names of temporary variables are gone, but the method within the target audience has always applied to the variable's value, and the value can only pass this way to visit. Even once again call the same constructor, but will only generate new objects and methods, and new temporary variable is just the corresponding new value, and the last calls that are separate. Very clever indeed!

But as we said, give each object a method is a huge waste. Have, "closure" to maintain such an indirect mechanism for variable values, often give the garbage collector JavaSript manufacturing problems. Objects are encountered particularly complex circular reference, the garbage collection to determine the logic is very complicated. Coincidentally, IE browser, the existence of an earlier version JavaSript trash recovery of memory leak problem. Coupled with the "closure" model of performance testing at the poor performance, Microsoft finally abandoned the "closure" model, and moving to a "prototype" model. The saying goes, "you win some and lose must" do.

Prototype model of the need for a constructor to define the members of the object, and methods of attachment are at the prototype of the constructor on. Generally written as follows:
/ / Define constructor
function Person (name)
(
this.name = name; / / in the constructor in the definition of a member of
);

/ / Method definition to the constructor of the prototype on
Person.prototype.SayHello = function ()
(
alert ( "Hello, I'm" + this.name);
);

/ / Subclass constructor
function Employee (name, salary)
(
Person.call (this, name); / / call constructor upper
this.salary = salary; / / expand the membership
);

/ / Subclass constructor required by the upper first constructor to set up prototype object, the concept of implementation inheritance
Employee.prototype = new Person () / / only required method of its prototype, a member of this object does not have any meaning!

/ / Subclass method definition to the constructor above
Employee.prototype.ShowMeTheMoney = function ()
(
alert (this.name + "$" + this.salary);
);

var BillGates = new Person ( "Bill Gates");
BillGates.SayHello ();

var SteveJobs = new Employee ( "Steve Jobs", 1234);
SteveJobs.SayHello ();
SteveJobs.ShowMeTheMoney ();

Although the prototype model category Analog should not really private variables, but also in two parts to define the categories, seems not very "elegant." However, object methods are shared, Recycling garbage problem is not encountered, and the performance is superior to "closure" model. Is the so-called "being there" with them.

In the prototype model, in order to achieve types of inheritance, you must first sub-class constructor's prototype is set to a parent class object instance. Create the parent object instance constituted for the purpose of the prototype chain to play a role in sharing the top prototype method. However, examples of the creation of this object, the upper constructor will set the object to its members, members of the succession of these objects is meaningless. Although we do not pass parameters to the constructor, but it does create a number of useless members, even though its value is undefined, this is a waste ah.

Alas! The world nothing is perfect ah!

Prototype of the true meaning of

Just as we were being overwhelmed with great, the red light flash together with the sky, clouds appear in the Goddess of Mercy. Jade saw her handheld Jingping, the breeze Tsui switchgrass, shed a few drops of mannose, suddenly let JavaScript Adds new Aura.

Guanyin shed at the mannose JavaScript condenses into the world of block and become a known as the "grammar Ganlu" things. This grammar allows us to prepare Ganlu code looks more like the target language.

To know that "grammar Ganlu" what, please listen citrinopileatus jun.

Mannose in the understanding of these grammar, we need to re-look at the process of JavaScript object structure.

We already know that using var anObject = new aFunction () form of the process of creating the object in fact can be divided into three steps: The first step is to set up a new object; the second step of the built-in object prototype object constructor prototype is set to invoke that the prototype object; The third step is the object as a parameter to call this constructor, the completion of the work of members of initialization settings. Set up after the object, the object on any access and manipulate only with the object itself and its prototype chain那串object, and again has nothing to do with the constructor relations. In other words, the constructor is only played in the creation of object prototype objects and introduce both the role of the object to initialize.

Well, we can come to their own definition of an object as a prototype, and on the prototype described in this category, and then set up the prototype to the newly created object, the object of its class as it? Can we afford to be the prototype of the constructor as a method to initialize a new object of it? For example, we have the definition of such a prototype object:
var Person = / / define an object as a prototype category
(
Create: function (name, age) / / The constructor function when
(
this.name = name;
this.age = age;
),
SayHello: function () / / definition of Ways
(
alert ( "Hello, I'm" + this.name);
),
HowOld: function () / / definition of Ways
(
alert (this.name + "is" + this.age + "years old.");
)
);

This form of writing JSON how like a C # class ah! Both constructor, and a variety of methods. If some form can be used to create objects, and built a prototype object is set to top the "Class" object, not to create a kind of equivalent to the object of it?

Unfortunately, we almost do not have access to the object prototype built property! While some browsers can visit to built a prototype object, but to do so can only limit the user must use the kind of browser. This is almost not feasible.

Then we can pass a function object to do the media, using the prototype property of function objects to transfer the prototype, and new operator of the object passed to the new do?

In fact, code like this can achieve this goal:
function anyfunc (){}; / / define a function body
anyfunc.prototype = Person; / / will be a transit point on the prototype object prototype
var BillGates = new anyfunc (); / / new object the prototype will be built is that we expect the prototype object

However, this anyfunc function is only a body, in the use of this body, after it became superfluous things, and this and direct the use of constructors to create objects also nothing different, a bit uncomfortable.

However, if we will be written in the code of a generic function, and the function body will become a function of function, the internal function not to be able to function at the outer scope exit automatically after the demise of it? Moreover, we can object as a generic function prototype parameters, so that common functions return the object created. What we need is the following forms:
function New (aClass, aParams) / / generic function to create
(
function new_ () / / definition of a temporary transit Shell function
(
aClass.Create.apply (this, aParams); / / call the prototype defined in the constructor, transit tectonic logic and structure parameters
);
new_.prototype = aClass; / / prepare interim prototype object
return new new_ (); / / return eventually set up set up the object
);

var Person = / / definition of class
(
Create: function (name, age)
(
this.name = name;
this.age = age;
),
SayHello: function ()
(
alert ( "Hello, I'm" + this.name);
),
HowOld: function ()
(
alert (this.name + "is" + this.age + "years old.");
)
);

var BillGates = New (Person, [ "Bill Gates", 53]); / / call the generic function to create objects and to form an array of structural parameters
BillGates.SayHello ();
BillGates.HowOld ();

alert (BillGates.constructor == Object); / / output: true

Here generic function New () is a "grammar Ganlu"! This grammar is not only a transit Ganlu prototype object, but also transit the constructor logic and structure parameters.

Interestingly, each created object exit New function scope, the temporary object new_ function will be automatically released. New_ because the prototype property is set to the new prototype object, its original objects and prototypes have been solved between the new_ quoted chain, temporary function and the original prototype of the object will be correctly recovered. The last sentence of the above code has proved that the newly created object constructor return of property are Object function. In fact, the object of a new prototype of themselves and their property do not have constructor, then return only the most top-level object constructor prototype, that is Object.

With this grammar New mannose, the definition of categories similar to C # on the static object that the form of language, so the code looks how quiet and elegant ah!

Of course, this code simply to display the "grammar Ganlu" concept. We also need more grammar mannose can be achieved with simplicity and elegance of the code writing class hierarchy and inheritance. Well, we will look at examples of a more extensive bar:
/ / Grammar Ganlu:
var object = / / definition of the object lowercase basic group, for the most basic way to achieve such
(
isA: function (aType) / / of a judge as well as between classes and categories of objects and the relationship between the basic types of Ways
(
var self = this;
while (self)
(
if (self == aType)
return true;
self = self.Type;
);
return false;
)
);

function Class (aBaseClass, aClassDefine) / / create a type of function, for the statement type and inheritance
(
function class_ () / / create a temporary function of the shell-type
(
this.Type = aBaseClass; / / we give each category a Type property agreement, citing its successor class
for (var member in aClassDefine)
this [member] = aClassDefine [member]; / / copy all the definition of category to the current category created
);
class_.prototype = aBaseClass;
return new class_ ();
);

function New (aClass, aParams) / / create the object function, for any type of object to create
(
function new_ () / / Create temporary function object shell
(
this.Type = aClass; / / We also agreed to each object a Type property, which can access the object belongs to category
if (aClass.Create)
aClass.Create.apply (this, aParams); / / we agreed that all types of constructor called Create, which is similar DELPHI
);
new_.prototype = aClass;
return new new_ ();
);

/ / Grammar Ganlu application results:
var Person = Class (object, / / derived from the basic types of object
(
Create: function (name, age)
(
this.name = name;
this.age = age;
),
SayHello: function ()
(
alert ( "Hello, I'm" + this.name + "," + this.age + "years old.");
)
));

var Employee = Class (Person, / / derived from Person class and the general are not very similar to the target language?
(
Create: function (name, age, salary)
(
Person.Create.call (this, name, age); / / Call base class constructor
this.salary = salary;
),
ShowMeTheMoney: function ()
(
alert (this.name + "$" + this.salary);
)
));

var BillGates = New (Person, [ "Bill Gates", 53]);
var SteveJobs = New (Employee, [ "Steve Jobs", 53, 1234]);
BillGates.SayHello ();
SteveJobs.SayHello ();
SteveJobs.ShowMeTheMoney ();

var LittleBill = New (BillGates.Type, [ "Little Bill", 6]); / / in accordance with the type of BillGate to create LittleBill
LittleBill.SayHello ();

alert (BillGates.isA (Person)); / / true
alert (BillGates.isA (Employee)); / / false
alert (SteveJobs.isA (Person)); / / true
alert (Person.isA (Employee)); / / false
alert (Employee.isA (Person)); / / true

"Ganlu grammar" not too much, as long as it a little bit, you can change the entire code legibility and fluency, so that code looks more elegant. With these grammar mannose, JavaScript on the target language very much like the general, and to write the code from the feeling of many of the cool it!

Happily, by these Ganlu nourish the JavaScript program will be higher efficiency. Object in its prototype because neither the useless members of those object-level and does not exist property constructor body, representing a drop of between function and structure implicated, but still maintained a shared method. This allows JavaScript retrospective at the prototype chain and search property and method, costs much less effort ah.

We took this form as "Ganlu model"吧! In fact, this "model Ganlu" prototype usage is in line with the prototype concept of intention is the essence of the prototype of JavaScript!

Microsoft AJAX presumably those who design architecture of the Engineer to see this Ganlu model, it will definitely not regret it as soon as possible put AJAX Our move from the United States Department of the Chinese Goddess of Mercy Temple, the Goddess of Mercy missed the modal. Of course, we are only at the code example, as Bill Gates put the object to play, I really want to make him give up the God Buddha certainly turn my conversion is not easy, the opportunity has not yet ah! If you day out at the new Microsoft AJAX Library to see this Ganlu model, that is the real缘分!

Programming Happiness

At the rapid development of the software industry today, a wide variety of programming languages and styles, the birth of new language, the old language of evolution, seems to have dazzled us. Object-oriented programming in order to adapt to the trend, JavaScript language is also to fully object-oriented development, the new JavaScript standard has been expanded from the semantic object-oriented lot of new elements. On the contrary, many static objects to the JavaScript language is also the kind of concise and elegant direction. For example, the new version of the C # language on the absorption of the JSON notation as concise, as well as some other forms of JavaScript features.

We should see, with the RIA (Strong Internet application) development and diffusion, AJAX technology also will be phased out Jianghu, JavaScript will eventually disappear or evolve into other forms of language. However, regardless of programming language development and evolution, programming the world will always be in the "data" and "code" This is a web of entangled maintained unlimited vitality. As long as we can see this point, we can easily study and understand the software world of new things. Regardless of the course are already familiar with programming, or is the development of Functional Programming, as well as the future of quantum entangled state of large-scale parallel programming, we have sufficient power to resolve all complex problems.

Finally faint Buddha said: As long as we put aside those superficial "category", put down those who object "self", will be able to reach a "target of the non-root, type also invisible" realm, which will self-integrate into the entire universe round cycle of life. We will not self, nor selfish desires, you are me, I am you, you have me, I have of you. At this time, we look at this dynamic programming world, our hearts will be naturally from the heart of unlimited love, the kindness of heart is not hypocrisy but sincere. Care for others is to love ourselves, love is everything in this world. Well, our hearts are never happy, and our procedures are always happy, we are of the type of Forever happy, our object is Forever happy. This is the programming of Paradise!

Here, the monks here are as if sobering, heart suddenly. Take a look at the left of the already喜不自禁, and then see who is right心花怒放.

Looking back, when suddenly, the only见君拈花微笑...