I have read a very good explanation of js functions.

Source: Internet
Author: User
Tags prototype definition
Author: F. Permadi
Introduction to JavaScript Functions
(Example): javascript Functions
Suhu Note: A very good articleFunctionThis is a classic article.

Word Translation list:If you want to publish this article, please indicate the location, without the right to publish the copyright, I do not like to see that kind of website my work does not indicate the person QQ9256114
Function: Function ( FunctionNot translated)
Declare: Definition
Assign: assign, assign
Functionbody: function body (the content of the function)
Object: Object
Property: property
Unnamed: anonymous (not translated as unnamed here)
Object oriented programming: surface relative phase programming
Class: class (for example, I translate the class data type to the class data type)
Pointer: pointer
Reassign: Reallocation
Nest: nesting
Feature: Features
Local/global: local/global
Blueprint: blueprint (?)
User defined: user-defined
Instance: instance
Prototype: prototype (no translation except the title)
Internal: internal
Constructor: constructor
Duplication:
Function: Define http://www.updateweb.cn

You can use the following methods to define a function. All of these are valid, but there are some differences in how they are implemented in the background.

Common Writing Method
This statement is generally used to define a function: functionName ([parameters]) {functionBody}; Example D1:
CODE:
FunctionAdd (a, B ){
Return a + B;
}
Alert (add (1, 2); // result 3

When we define a function like this, the function content will be compiled (but will not be executed immediately unless we call it ). Besides, you may not know that when this function is created, there is a function with the same name.ObjectIs also created. In our example, we now haveObjectIt is called "add" (for more information, see the following functions:Object.)
Anonymous Functions

You can also define a variable by assigning it to an anonymous function.
Example D2 var add =Function(A, B ){
Return a + B;
}
Alert (add (1, 2); // result 3

This code is the same as the previous example. Maybe the syntax looks strange, but it should make you feel that the function isObjectAnd we only assigned a name for this pair. We can regard it as the same statement as var myVar = [, 3. The function content declared in this way will also be compiled.

When we assign such a function, we do not necessarily need to be an anonymous function. Here, I did the same thing as ExampleD2, but I added the function name "theAdd", and I can reference the function by calling the function name or the variable.

Example D2Avar add =FunctionTheAdd (a, B ){
Return a + B;
}
Alert (add (1, 2); // result 3
Alert (theAdd (1, 2); // The result is also 3.

To define a function in this wayObjectProgramming is very useful, because we can make a function as below intoObject. Var myObject = new Object ();
MyObject. add =Function(A, B) {return a + B };
// MyObject now has an attribute (or method) called "add)
// And I can use it like below
MyObject. add (1, 2 );

We can also define a function by using the new operator. This is the most rare way to define a function and is not recommended unless for special reasons (for possible reasons, see below ). Syntax: varName = newFunction([Param1Name, param2Name,... paramNName], functionBody );
Example D3:

Var add = newFunction("A", "B", "return a + B ;");
Alert (add (3, 4); // result 7

I have two parameters here: a and B, and the function body returns the sum of a and B. Please note that newFunction(...) Use upper-case F instead of lower-case f. This tells javascript that we will create a type that isFunctionOfObject.

Note that both the parameter name and function body are passed as strings. We can add parameters as needed. javascript knows that the function is the last string before the right brackets (if no

With parameters, you can write only the function body ). You do not need to write everything in one line (use \ or use string connector + to separate long code ). \ Mark to tell JavaScript to query the next line
Find the rest of the string. Example:

Example D4 var add = new Function ("a", "B ",
"Alert" + // note "+"
"('Adding' + a + 'and' + B); return a + B;"); // different usage from "\"
Alert (add (3, 4); // result 7 defining a function in this way will cause the function to be not compiled, and it may be slower than defining a function in other ways. As for why, let's take a look at this Code:

Example D5FunctionCreateMyFunction (myOperator ){
Return newFunction("A", "B", "return a" + myOperator + "B ;");
}
Var add = createMyFunction ("+"); // create a function "add"
Var subtract = createMyFunction ("-"); // create a function "subtract"
Var multiply = createMyFunction ("*"); // create a function "multiply"
// Test the functions
Alert ("added result =" + add (); // The result is 12
Alert ("subtraction result =" + subtract (); // The result is 8
Alert ("Multiplication result =" + multiply (10, 2); // The result is 20
Alert (add );

This interesting example creates three differentFunctionBy passing different parameters in real time to create a newFunction. Because the compiler cannot know what the final code looks like, so newFunction(...)

Will not be compiled. So what are the benefits? Well, for example, if you want users to create their own functions, this function may be useful, for example, in the game. We may need to allow
Add "behavior" to a "player ". However, once again, we should avoid using this form unless there is a special purpose.

Function:Object
A function is a special form in javascript.Object. It is the first [B] class data type ). This means that we can add attributes to it. Here are some interesting points to note:

Object.
As mentioned earlier, when we define a function, javascript actually createsObject. ThisObjectIs the function name itself. ThisObjectIsFunction. In the following example, we may not realize this, but we have actually createdObject: It is called Ball.

Example 1FunctionBall () {// It may seem a bit strange, but this statement createsObject
I = 1;
}
Alert (typeof Ball); // result"Function"

We can evenObjectAnd it will output the actual code of this function. Example2: Click alert (Ball); to see the Ball content.

Add attribute
We can add attributes to the Object, includingObjectFunction. Because the essence of defining a function is to createObject. We can "secretly" add attributes to the function. For example, we define the function Ball and add the callsign attribute.FunctionBall () // It may seem a bit strange, but this statement
{// Creates a BallObjectAnd you can
} // Reference it or add attributes to it as follows
Ball. callsign = "The Ball"; // Add attributes to The Ball
Alert (Ball. callsign); // output "The Ball"

Pointer
BecauseFunctionIsObject, We canFunctionAssign a pointer. In the following example, the variable ptr pointsObjectMyFunction.FunctionMyFunction (message ){
Alert (message );
}
Var ptr = myFunction; // ptr points to myFunction
Ptr ("hello"); // This statement will execute myFunction: output "hello"

We can run this function as if the function name has been replaced by the pointer name. So above, the ptr ("hello"); and myFunction ("hello"); have the same meaning.
The pointer to the function isObjectProgramming is quite useful. For example, when we have multipleObjectWhen pointing to the same function (as follows ):

Example 4AFunctionSayName (name ){
Alert (name );
}
Var object1 = new Object (); // create threeObject
Var object2 = new Object ();
Var object3 = new Object ();
Object1.sayMyName = sayName; // assign this function to allObject
Object2.sayMyName = sayName;
Object3.sayMyName = sayName;

Object1.sayMyName ("object1"); // output "object1"
Object2.sayMyName ("object2"); // output "object2"
Object3.sayMyName ("object3"); // output "object3"

Because only the pointer is saved (not the function itself), when we change the functionObjectIn itself, all pointers to that function will change. We can see below:
Example 5:FunctionMyFunction (){
Alert (myFunction. message );
}
MyFunction. message = "old ";
Var ptr1 = myFunction; // point to myFunction
Var ptr2 = myFunction; // ptr2 also points to myFunction

Ptr1 (); // output "old"
Ptr2 (); // output "old"
MyFunction. message = "new ";
Ptr1 (); // output "new"
Ptr2 (); // output "new"

Pointer pointing
We can re-allocate a function after it is created, but we need to point to the FunctionObjectInstead of pointing to its pointer. In the following example, I will change the content of myfunction.

Example 6:FunctionMyFunction (){
Alert ("Old ");
}
MyFunction (); // output "Old"
MyFunction =Function(){
Alert ("New ");
};
MyFunction (); // output "New"

Where are the old functions ?? Abandoned.

If we need to keep it, we can assign a pointer to it before changing it.

Example 6A:FunctionMyFunction (){
Alert ("Old ");
}
Var savedFuncion = myFunction;
MyFunction =Function(){
Alert ("New ");
};
MyFunction (); // output "New"
SavedFuncion (); // output "Old"

However, be careful that the example below does not work, because another function called myFunctionPtr is created rather than modified.

Example 6B:FunctionMyFunction (){
Alert ("Old ");
}
Var savedFunc = myFunction;
SavedFunc =Function(){
Alert ("New ");
};
MyFunction (); // output "Old"
SavedFunc (); // output "New"

Embedded Functions
We can also nest a function in a function. In the following example, I have a function called getHalfOf, and in it, I have another function called calculate.

Example 7FunctionGetHalfOf (num1, num2, num3 ){
FunctionCalculate (number ){
Return number/2;
}
Var result = "";
Result + = calculate (num1) + "";
Result + = calculate (num2) + "";
Result + = calculate (num3 );
}
Var resultString = getHalfOf (10, 20, 30 );
Alert (resultString); // output "5 10 15"

You
Nested functions can only be called internally. That is to say, you cannot call: getHalfOf. calculate (10), because calculate is only used when an external Function
(GetHalfOf () exists only during running. This is consistent with the previous discussion (the function will be compiled, but it will be executed only when you call it ).

Which function is called?
You may be thinking about naming conflicts. For example, which of the following functions is called calculate?

Example 8FunctionCalculate (number ){
Return number/3;
}

FunctionGetHalfOf (num1, num2, num3 ){
FunctionCalculate (number ){
Return number/2;
}

Var result = "";
Result + = calculate (num1) + "";
Result + = calculate (num2) + "";
Result + = calculate (num3 );
}
Var resultString = getHalfOf (10, 20, 30 );
Alert (resultString); // output "5 10 15"

In this example, the compiler first searches for the local memory address, so it uses the embedded calculate function. If we delete this built-in (local) calculate function, this Code uses the Global calculate function.

Function: Data Type and constructor
Let's take a look at another special function of the function -- this makes it and otherObjectDifferent types. A function can be used as a blueprint for a data type. This feature is usually usedObjectProgram to simulate user-defined data type ). Created using a user-defined data typeObjectUsually become user-definedObject(User defined object ).

Data Type
After defining a function, we also create a new data type. This data type can be used to create a newObject. In the following example, a new data type called Ball is created.

Example DT1FunctionBall (){
}
Var ball0 = new Ball (); // ball0 now points to a newObject
Alert (ball0); // output "Object", because ball0 is nowObject

So what does ball0 = new Ball () do? The new Keyword creates a new Object typeObject(Called ball0 ). Then it executes Ball () and passes the reference to ball0 (used to callObject). Next, you will see this message: "creating new Ball", if Ball () is actually running.

Example DT2FunctionBall (message ){
Alert (message );
}
Var ball0 = new Ball ("creating new Ball"); // createObjectAnd output messages
Ball0.name = "ball-0"; // ball0 now has an attribute: name
Alert (ball0.name); // output "ball-0"

We can think of the 6th lines of the above Code as a shorthand for the 6-8 lines of the following code:FunctionBall (message ){
Alert (message );
}
Var ball0 = new Object ();
Ball0.construct = Ball;
Ball0.construct ("creating new ball"); // execute ball0.Ball ("creating ..");
Ball0.name = "ball-0 ";
Alert (ball0.name );

This line of code ball0.construct = Ball is consistent with the ptr = myFunction syntax in Example 4.

If you still don't understand the meaning of this line, go back and review Example 4. Note: You may consider directly running ball0.Ball ("... "), but it does not work, because ball0 does not have a Ball ("... "), and it does not know what you want to do.

Add attribute
When we use the keyword new as above to createObjectA new Object is created. We can give thisObjectAdd attributes (as if I had added the attribute name as above. The next question is, if we create thisObjectAnother instance, we have to give this new instance again as belowObjectAdd this attribute .)

Example DT3 (creates 3 ball objects)FunctionBall (){
}
Var ball0 = new Ball (); // ball0 now points to a new instance of the type Ball
Ball0.name = "ball-0"; // ball0 now has an attribute "name"
Var ball1 = new Ball ();
Ball1.name = "ball-1 ";
Var ball2 = new Ball ();
Alert (ball0.name); // output "ball-0"
Alert (ball1.name); // output "ball-1"
Alert (ball2.name); // Oh, I forgot to add "name" to ball2!

I forgot to add the attribute name to ball2. If it is in a formal program, this may cause problems. Is there any good way to automatically add attributes? Well, there is one: Use the this keyword. The word "this" appears inFunctionIt has special significance. It points to the one that calls the function.Object. Let's take a look at another example below. At this time, we add these attributes to the constructor:

Example DT4FunctionBall (message, specifiedName ){
Alert (message );
This. name = specifiedName;
}
Var ball0 = new Ball ("creating new Ball", "Soccer Ball ");
Alert (ball0.name); // prints "Soccer Ball"

Remember: The new Keyword eventually executes the constructor. In this example, it will run Ball ("creating new Ball", "Soccer Ball"), and the keyword this will point to ball0.
Therefore, this line: this. name = specifiedName is changed to ball0.name = "Soccer Ball ".
It mainly refers to adding the attribute name to ball0 and the attribute value is Soccer Ball.
Now we just added a name attribute to ball0, which looks like what we did in the previous example, but it is a better and more scalable method. Now, we can create many balls with attributes as we like without manually adding them. In addition, people also want to create BallObjectIt can clearly understand its constructor and easily find all the attributes of Ball. Let's add more attributes to Ball.

Example DT5FunctionBall (color, specifiedName, owner, weight ){
This. name = specifiedName;
This. color = color;
This. owner = owner;
This. weight = weigth;
} If you want to publish this article, please indicate the origin site, and the copyright holder is free of charge. I do not like to see this website. My work does not indicate the owner QQ9256114.
Var ball0 = new Ball ("black/white", "Soccer Ball", "John", 20 );
Var ball1 = new Ball ("gray", "Bowling Ball", "John", 30 );
Var ball2 = new Ball ("yellow", "Golf Ball", "John", 55 );
Var balloon = new Ball ("red", "Balloon", "Pete", 10 );

Alert (ball0.name); // output "Soccer Ball"
Alert (balloon. name); // output "Balloon"
Alert (ball2.weight); // output "55"

Hey! Usage orientedObjectTerm, you can say that a Ball has the following attributes:ObjectType: name, color, owner, weight.

SetObjectAttribute assigned
We are not limited to adding simple data types such as strings or numbers as attributes. We can alsoObjectAttribute. The supervisor is an attribute of the Employee.

Example DT6FunctionEmployee (name, salary, mySupervisor ){
This. name = name;
This. salary = salary;
This. supervisor = mySupervisor;
}
Var boss = new Employee ("John", 200 );
Var manager = new Employee ("Joan", 50, boss );
Var teamLeader = new Employee ("Rose", 50, boss );
Alert (manager. supervisor. name + "is the supervisor of" + manager. name );
Alert (manager. name + "\'s supervisor is" + manager. supervisor. name );

What will be output?
As you can see in the preceding example, both manager and teamLeader have a supervisor attribute, which is a type of Employee.Object.

Use functions as attributes
Any typeObjectCan be used as an attribute to recall the previous Example 4 (not Example DT4), and the function is alsoObject. So you can make a functionObject. Next, I will add two functions: getSalary and addSalary.

Example DT7FunctionEmployee (name, salary ){
This. name = name;
This. salary = salary;
This. addSalary = addSalaryFunction;
This. getSalary =Function(){
Return this. salary;
};
}
FunctionAddSalaryFunction (addition ){
This. salary = this. salary + addition;
}
Var boss = new Employee ("John", 200000 );
Boss. addSalary (10000); // The boss has a salary of 10 K ...... Why can the boss pay so much :'(
Alert (boss. getSalary (); // output 210 K ...... Why is the default salary so high ...... :'(

AddSalary and getSalary demonstrate several different methods for assigning functions to attributes. If you remember what we discussed at the beginning, I discussed the different methods for declaring the three functions. All those are applicable here, but the two shown above are the most commonly used.

Let's see what's different. Next, pay attention to the 9-12 lines of code. When this part of the code is executed, the getSalary function is declared. As mentioned earlier, the result of a function declaration isObjectCreated. So at this time, the boss is created (the next 19th rows), and the boss has a getSalary attribute.FunctionEmployee (name, salary ){
This. name = name;
This. salary = salary;
This. addSalary = addSalaryFunction;

This. getSalary =Function(){
Return this. salary;
};
}
FunctionAddSalaryFunction (addition ){
This. salary = this. salary + addition;
}

Var boss = new Employee ("John", 200000 );
Var boss2 = new Employee ("Joan", 200000 );
Var boss3 = new Employee ("Kim", 200000 );

When you create thisObjectFor more instances (boss2 and boss3), each instance has a separate copy of The getSalary code. In contrast, addSalary points to the same place (that is, addSalaryFunction ).

Take a look at the following code to understand the content described above.

Example DT8FunctionEmployee (name, salary ){
This. name = name;
This. salary = salary;

This. addSalary = addSalaryFunction;
This. getSalary =Function(){
Return this. salary;
};
}
FunctionAddSalaryFunction (addition ){
This. salary = this. salary + addition;
}

Var boss1 = new Employee ("John", 200000 );
Var boss2 = new Employee ("Joan", 200000 );

// Call the getSalary FunctionObjectAdd attribute
Boss1.getSalary. owner = "boss1 ";
Boss2.getSalary. owner = "boss2 ";
Alert (boss1.getSalary. owner); // output "boss1"
Alert (boss2.getSalary. owner); // output "boss2"
// If twoObjectPoint to the same functionObject, Then
// Both outputs must be "boss2 ".

// Give the addSalary FunctionObjectAdd attribute
Boss1.addSalary. owner = "boss1 ";
Boss1.addSalary. owner = "boss2 ";
Alert (boss1.addSalary. owner); // output "boss2"
Alert (boss2.addSalary. owner); // output "boss2"
// Because twoObjectAll point to the same function.Function, False positive)
// When one of them is modified, all instances are affected (so both instances output "boss2 ").

It may not be important, but here are some conclusions about running built-in functions similar to getSalary: 1) more storage space is needed to storeObject(Because everyObjectThe instance will have its own getSalary code copy); 2) javascript needs more time to construct thisObject.

Let's rewrite this example to make it more efficient.

Example DT9FunctionEmployee (name, salary ){
This. name = name;
This. salary = salary;

This. addSalary = addSalaryFunction;
This. getSalary = getSalaryFunction;
}
FunctionGetSalaryFunction (){
Return this. salary;
}

FunctionAddSalaryFunction (addition ){
This. salary = this. salary + addition;
}

Here, both functions point to the same place, which saves space and shortens the construction time (especially when you have a lot of built-in functions in one constructor ). Another function can be used to improve the design. It is called prototype, and we will discuss it in the next section.

Function: Prototype
Each constructor has a prototype attribute (prototype, which is not translated in the following example and is used in the original document ). This attribute is very useful: declare a common variable or function for a specific class.

Prototype Definition
You do not need to explicitly declare a prototype attribute because it exists in every constructor. You can look at the following example:

Example PT1FunctionTest (){
}
Alert (Test. prototype); // output "Object"

Add properties to prototype
As you can see above, prototype isObjectTherefore, you can add attributes to it. The property you added to prototype will be created using this constructor.Object.
For example, I have a data type Fish below, and I want all Fish to have these attributes: livesIn = "water" and price = 20; to achieve this, I can add those attributes to the prototype of the constructor Fish.
Example PT2FunctionFish (name, color ){
This. name = name;
This. color = color;
}
Fish. prototype. livesIn = "water ";
Fish. prototype. price = 20;

Next let's make a few Fish: var fish1 = new Fish ("macarel", "gray ");
Var fish2 = new Fish ("goldfish", "orange ");
Var fish3 = new Fish ("salmon", "white ");

Let's take a look at the attributes of fish: for (int I = 1; I <= 3; I ++ ){
Var fish = eval ("fish" + I); // I just get a pointer pointing to this fish
Alert (fish. name + "," + fish. color + "," + fish. livesIn + "," + fish. price );
}

The output should be: "macarel, gray, water, 20"
"Goldfish, orange, water, 20"
"Salmon, white water, 20"

You can see that all fish have the attributes livesIn and price, and we didn't even specifically declare these attributes for each different fish. In this case, whenObjectWhen the constructor is created, the constructor will assign its property prototype to the newObjectInternal attribute _ proto _ __. This _ proto _ isObjectUsed to find its attributes.

You can also use prototypeObjectAdd a shared function. This has one advantage: you do not need to constructObjectCreate and initialize this function. To explain this, let's repeat Example DT9 and rewrite it using prototype:

Use prototypeObjectAdd function

Example PT3FunctionEmployee (name, salary ){
This. name = name;
This. salary = salary;
}
Employee. prototype. getSalary =FunctionGetSalaryFunction (){
Return this. salary;
}

Employee. prototype. addSalary =FunctionAddSalaryFunction (addition ){
This. salary = this. salary + addition;
}

We can createObject: Var boss1 = new Employee ("Joan", 200000 );
Var boss2 = new Employee ("Kim", 100000 );
Var boss3 = new Employee ("Sam", 150000 );

Verify it: alert (boss1.getSalary (); // output 200000
Alert (boss2.getSalary (); // output 100000
Alert (boss3.getSalary (); // output 150000

Here is an illustration to illustrate how prototype works. ThisObjectEvery instance (boss1, boss2, boss3) has an internal attribute named _ proto __, which points to the prototype of its constructor (Employee. When you execute getSalary or addSalaryObjectThe code will be found and executed in its _ proto. Note: No code is copied here (compared with the chart Example DT8 ).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.