Javascript function Author: F. Permadi
Translator: Sheneyan (zi Wu)
Time: 2006.01.03
Introduction to JavaScript Functions
(Example): javascript Functions
Zi wunote: This is a very good function getting started article. I personally think it is quite classic.
Word Translation list
Function: Function (function not 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: defined
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.
Generally, we use this syntax to define a function:
[Copy to clipboard] CODE:
FunctionName ([parameters]) {functionBody };
Example D1:
[Copy to clipboard] CODE:
Function add (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 ). You may not know that an object with the same name is also created when this function is created. In our example, we now have an object called "add" (for more information, see function: Object section .)
You can also define a variable by assigning it to an anonymous function.
Example D2
[Copy to clipboard] CODE:
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 is an object, and we just 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 D2A
[Copy to clipboard] CODE:
Var add = function theAdd (a, B)
{
Return a + B;
}
Alert (add (1, 2); // result 3
Alert (theAdd (1, 2); // The result is also 3.
Defining a function in this way is very useful in Object-Oriented Programming, because we can make a function an object attribute as below.
[Copy to clipboard] CODE:
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:
[Copy to clipboard] CODE:
VarName = new Function ([param1Name, param2Name,... paramNName], functionBody );
Example D3:
[Copy to clipboard] CODE:
Var add = new Function ("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. Note that new Function (...) uses uppercase F instead of lowercase f. This tells javascript that we will create an object of Function type. Note that both the parameter name and function body are passed as strings. We can add parameters as we like. javascript knows that the function is the last string before the right bracket (if there is no parameter, you can write only the function body ). You do not need to write everything in one line (use or use the string connector + to separate long code ). Mark to tell JavaScript to look for the rest of the string in the next line. Example:
Example D4
[Copy to clipboard] CODE:
// Note "+"
// Different usage from "\"
Var add = new Function ("a", "B ",
"Alert" +
"('Adding' + a + 'and' + B );\
Return a + B ;");
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 D5
[Copy to clipboard] CODE:
Function createMyFunction (myOperator)
{
Return new Function ("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 different functions and creates a new function by passing different parameters in real time. Because the compiler cannot know what the final code looks like, the content of new Function (...) 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 users to add "actions" 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 of Object in javascript. It is the first [B] class data type ). This means that we can add attributes to it. Here are some interesting points to note:
As mentioned earlier, when we define a function, javascript actually creates an object for you in the background. The object name is the function name. The object type is function. In the following example, we may not realize this, but we have actually created an object called Ball.
Example 1
[Copy to clipboard] CODE:
Function Ball () // It may seem a bit strange, but this statement
{// Creates an object called Ball.
I = 1;
}
Alert (typeof Ball); // result "function"
We can even print the content of this object and it will output the actual code of this function. Example 2: Click alert (Ball); to see the content of Ball.
We can add attributes to an Object, including the Object function. Because the essence of defining a function is to create an object. We can "secretly" add attributes to the function. For example, we define the function Ball and add the callsign attribute.
[Copy to clipboard] CODE:
Function Ball () // It may seem a bit strange, but this statement
{// Creates an object called Ball, and 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"
Because function is an object, we can assign a pointer to a function. In the following example, the variable ptr points to the object myFunction.
[Copy to clipboard] CODE:
Function myFunction (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.
Pointers to functions are quite useful in object-oriented programming. For example, when multiple objects point to the same function (as shown below ):
Example 4A
[Copy to clipboard] CODE:
Function sayName (name)
{
Alert (name );
}
Var object1 = new Object (); // create three objects
Var object2 = new Object ();
Var object3 = new Object ();
Object1.sayMyName = sayName; // assign this function to all objects
Object2.sayMyName = sayName;
Object3.sayMyName = sayName;
Because only the pointer is saved (rather than the function itself), when we change the function object itself, all pointers pointing to that function will change. We can see below:
Example 5:
[Copy to clipboard] CODE:
Function myFunction ()
{
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"
We can re-allocate a function after it is created, but we need to point to the function object rather than its pointer. In the following example, I will change the content of myfunction.
If we need to keep it, we can assign a pointer to it before changing it.
Example 6A:
[Copy to clipboard] CODE:
Function myFunction ()
{
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:
[Copy to clipboard] CODE:
Function myFunction ()
{
Alert ("Old ");
}
Var savedFunc = myFunction;
SavedFunc = function ()
{
Alert ("New ");
};
MyFunction (); // output "Old"
SavedFunc (); // output "New"
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 7
[Copy to clipboard] CODE:
Function getHalfOf (num1, num2, num3)
{
Function calculate (number)
{
Return number/2;
}
Var result = "";
Result + = calculate (num1) + "";
Result + = calculate (num2) + "";
Result + = calculate (num3 );
Return result;
}
Var resultString = getHalfOf (10, 20, 30 );
Alert (resultString); // output "5 10 15"
You can only call nested functions internally. That is to say, you cannot call getHalfOf. calculate (10) Because calculate exists only when the external function (getHalfOf () is running. This is consistent with the previous discussion (the function will be compiled, but it will be executed only when you call it ).
You may be thinking about naming conflicts. For example, which of the following functions is called calculate?
Example 8
[Copy to clipboard] CODE:
Function calculate (number)
{
Return number/3;
}
Function getHalfOf (num1, num2, num3)
{
Function calculate (number)
{
Return number/2;
}
Var result = "";
Result + = calculate (num1) + "";
Result + = calculate (num2) + "";
Result + = calculate (num3 );
Return result;
}
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-which makes it different from other object types. A function can be used as a blueprint for a data type. This feature is usually used in Object-Oriented Programming to simulate user-defined data types ). Objects Created using user-defined data types are usually user-defined objects ).
After defining a function, we also create a new data type. This data type can be used to create a new object. In the following example, a new data type called Ball is created.
Example DT1
[Copy to clipboard] CODE:
Function Ball ()
{
}
Var ball0 = new Ball (); // ball0 now points to a new object
Alert (ball0); // output "Object", because ball0 is an Object now
So what does ball0 = new Ball () do? The new Keyword creates a new Object (called ball0) of the Object type ). Then it executes Ball () and passes the reference to ball0 (used to call the object ). Next, you will see this message: "creating new Ball", if Ball () is actually running.
Example DT2
[Copy to clipboard] CODE:
Function Ball (message)
{
Alert (message );
}
Var ball0 = new Ball ("creating new Ball"); // create an object and output a message
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:
[Copy to clipboard] CODE:
Function Ball (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.
When we use the keyword new to create an Object as above, a new Object is created. We can add attributes to this object after the object is created (as if I have added the attribute name as above. The next problem is that if we create another instance of this object, we have to add this attribute to this new object as follows .)
Example DT3 (creates 3 ball objects)
[Copy to clipboard] CODE:
Function Ball ()
{
}
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. This word has special significance in function. It points to the object that calls the function. Let's take a look at another example below. At this time, we add these attributes to the constructor:
Example DT4
[Copy to clipboard] CODE:
Function Ball (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 hope that the Ball object can clearly understand its constructor and easily find all the attributes of the Ball. Let's add more attributes to Ball.
Example DT5
[Copy to clipboard] CODE:
Function Ball (color, specifiedName, owner, weight)
{
This. name = specifiedName;
This. color = color;
This. owner = owner;
This. weight = weight;
}
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 );
Hey! Using object-oriented terminology, you can say that Ball is an object type with the following attributes: name, color, owner, and weight.
We are not limited to adding simple data types such as strings or numbers as attributes. We can also assign objects to attributes. The supervisor is an attribute of the Employee.
Example DT6
[Copy to clipboard] CODE:
Function Employee (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 an object of the type of Employee.
Any type of object can be used as an attribute. Recall the previous Example 4 (not Example DT4), and the function is also an object. Therefore, you can use a function as an attribute of an object. Next, I will add two functions: getSalary and addSalary.
Example DT7
[Copy to clipboard] CODE:
Function Employee (name, salary)
{
This. name = name;
This. salary = salary;
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 previously, the result of a function declaration is that an object is created. So at this time, the boss is created (the next 19th rows), and the boss has a getSalary attribute.
[Copy to clipboard] CODE:
Function Employee (name, salary)
{
This. name = name;
This. salary = salary;
Var boss = new Employee ("John", 200000 );
Var boss2 = new Employee ("Joan", 200000 );
Var boss3 = new Employee ("Kim", 200000 );
When you create more instances of this object (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 DT8
[Copy to clipboard] CODE:
Function Employee (name, salary)
{
This. name = name;
This. salary = salary;
Var boss1 = new Employee ("John", 200000 );
Var boss2 = new Employee ("Joan", 200000 );
// Add attributes to the getSalary function object
Boss1.getSalary. owner = "boss1 ";
Boss2.getSalary. owner = "boss2 ";
Alert (boss1.getSalary. owner); // output "boss1"
Alert (boss2.getSalary. owner); // output "boss2"
// If two objects direct to the same function object
// Both outputs must be "boss2 ".
// Add attributes to the addSalary function object
Boss1.addSalary. owner = "boss1 ";
Boss1.addSalary. owner = "boss2 ";
Alert (boss1.addSalary. owner); // output "boss2"
Alert (boss2.addSalary. owner); // output "boss2"
// Because both objects point to the same function (sub-Note: In the original text, are not pointing to the same function, which is a 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 nested functions similar to the above getSalary: 1) more storage space is required to store objects (because each object instance has its own getSalary code copy). 2) javascript needs more time to construct this object.
Let's rewrite this example to make it more efficient.
Example DT9
[Copy to clipboard] CODE:
Function Employee (name, salary)
{
This. name = name;
This. salary = salary;
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.
You do not need to explicitly declare a prototype attribute because it exists in every constructor. You can look at the following example:
Example PT1
[Copy to clipboard] CODE:
Function Test ()
{
}
Alert (Test. prototype); // output "Object"
As you can see above, prototype is an object, so you can add attributes to it. The property you add to prototype will become a common property of the object created using this constructor.
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 PT2
[Copy to clipboard] CODE:
Function Fish (name, color)
{
This. name = name;
This. color = color;
}
Fish. prototype. livesIn = "water ";
Fish. prototype. price = 20;
Next let's make a few fish:
[Copy to clipboard] CODE:
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:
[Copy to clipboard] CODE:
For (var 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:
[Copy to clipboard] CODE:
"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, when an object is created, this constructor will assign its property prototype to the internal attribute _ proto _ of the new object __. This _ proto _ is used by this object to find its attributes.
You can also use prototype to add common functions to all objects. This has one benefit: you do not need to create and initialize this function every time you construct an object. To explain this, let's repeat Example DT9 and rewrite it using prototype:
Example PT3
[Copy to clipboard] CODE:
Function Employee (name, salary)
{
This. name = name;
This. salary = salary;
}
Employee. prototype. getSalary = function getSalaryFunction ()
{
Return this. salary;
}
[Copy to clipboard] CODE:
Var boss1 = new Employee ("Joan", 200000 );
Var boss2 = new Employee ("Kim", 100000 );
Var boss3 = new Employee ("Sam", 150000 );
Here is an illustration to illustrate how prototype works. Every instance of this object (boss1, boss2, boss3) has an internal attribute named _ proto __, which points to the prototype of its constructor (Employee. When you execute getSalary or addSalary, this object will find and execute this code in its _ proto. Note: No code is copied here (compared with the chart Example DT8 ).
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.