Page 1/3 of javascript Functions

Source: Internet
Author: User

Author: F. Permadi
Translator: Sheneyan (zi Wu)
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.

Common Writing Method

Generally, we use this syntax to define a function:

CODE:
FunctionName ([parameters]) {functionBody };

Example D1:

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 .)

Anonymous Functions

You can also define a variable by assigning it to an anonymous function.

Example D2

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

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.

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:

CODE:
VarName = new Function ([param1Name, param2Name,... paramNName], functionBody );

Example D3:

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 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

CODE:
Var add = new Function ("a", "B ",
"Alert" + // note "+"
"('Adding' + a + 'and' + B); \ // different usage "\"
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

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:

Object Creation

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

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. Example2: Click alert (Ball); to see the content of Ball.

Add attribute

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.

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"

Pointer

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.

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

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;

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

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:

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"

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.