Home  >  Article  >  Web Front-end  >  JavaScript functions_basic knowledge

JavaScript functions_basic knowledge

WBOY
WBOYOriginal
2016-05-16 19:20:08781browse

Author: F. Permadi
Translator: Sheneyan (Ziwu)
Time: 2006.01.03
English original text: INTRODUCTION TO JavaScript Functions
Chinese translation (including examples): javascript functions
Ziwu's note: A pretty good introductory article on function, I personally feel it is quite classic.

Word translation list
function: function (Function is not translated)
declare: definition
assign: assignment, allocation
functionbody: function body (that is, the content of the function)
object: object
property: attribute
unnamed: anonymous (not translated as unnamed here)
object oriented programming: oriented relative programming
class: class (for example, I translated the following class data type into a class data type)
pointer: pointer
reassign: reassignment
nest: nesting
feature: function, characteristic
local/global: local/global
blueprint: blueprint ( ? )
user defined: user-defined
instance: instance
prototype: prototype (except for the title)
internal: internal
constructor: constructor
duplication:

Function: Definition

There are the following methods to define a function. All of these are valid, but there are some differences in how they are implemented under the hood.

Usually everyone uses this writing method to define a function:


[Copy to clipboard]CODE:
functionName([parameters]){functionBody};

Example D1:


[Copy to clipboard]CODE:
function add(a, b)                                                                                                     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). Moreover, maybe you don't know, when this function is created, an object with the same name is also created. For our example, we now have an object called "add" (to learn more about it, see the Functions: Objects section below.)
We can also define an anonymous function by assigning a variable name to it.

Example D2


[Copy to clipboard]CODE:
var add=function(a, b)
{                                                                       
alert(add(1,2));    // Result 3

This code does the same thing as the previous example. Maybe the syntax looks weird, but it should give you a better sense that the function is an object, and we just assigned a name to the pair. It can be thought of as the same statement as var myVar=[1,2,3]. Function contents declared in this way will also be compiled.
When we assign such a function, we do not necessarily require it 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 that variable.

Example D2A


[Copy to clipboard]CODE:
var add=function theAdd(a, b)
{                                                                         }                                                                                                                                  This is very useful in object-oriented programming because we can make a function a property of an object like below.


[Copy to clipboard]CODE:
var myObject=new Object();
myObject.add=function(a,b){return a b};
// myObject now has a property (or method) called "add"
// and I can use it like this
myObject.add(1, 2);

We can also use Operator new to define a function. This is the least common way of defining a function and is not recommended unless there are specific reasons (see below for possible reasons).The syntax is as follows:


[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 called a and b, and the function body returns the sum of a and b. Please note that new Function(...) uses uppercase F instead of lowercase f. This tells javascript that we are going to create an object of type Function. Also note that parameter names and function bodies are passed as strings. We can add parameters as we like, and JavaScript knows that the function body is the last string before the right bracket (if there are no parameters, you can just write the function body). You don't have to write everything on one line (use or use string concatenation to separate long codes). The tag tells JavaScript to look for the rest of the string on the next line. The example is as follows:

Example D4


[Copy to clipboard]CODE:
// Note the different usages of " "
// and ""
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 not be compiled, and it may be slower than functions defined in other ways. As for why, 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 function "add"
var subtract=createMyFunction("-"); // Create function "subtract"
var multiply=createMyFunction("*"); // Create function "multiply"
// test the functions
alert(" The result of addition=" add(10,2)); //The result is 12
alert("The result of subtraction=" subtract(10,2)); // The result is 8
alert("Multiply Result=" multiply(10,2)); // The result is 20
alert(add);

This interesting example creates three different functions, created by passing different parameters in real time A new Function. Because the compiler has no way of knowing what the final code will look like, the contents of new Function(...) will not be compiled. So what's the benefit? Well, for example, this might be useful if you need users to be able to create their own functions, like in a game. We may need to allow users to add "behaviors" to a "player".But, again, generally we should avoid using this form unless there is a specific purpose.


Function: Object
Function is a special form of object in JavaScript. It is the first [b] class data type. This means we can add properties to it. Here are some interesting points to note:

As mentioned earlier, when we define a function, JavaScript actually creates an object for you behind the scenes. The name of this object is the function name itself. The type of this object is function. In the following example, we may not realize it, but we have actually created an object: it's called Ball.

Example 1


[Copy to clipboard]CODE:
function Ball() // Maybe it looks a little strange, but this declaration An object called Ball
i=1;
}                                                                Output the actual code of this function, Example 2: Click alert(Ball); to see the contents of Ball.
We can add properties to Object, including object functions. Because the essence of defining a function is to create an object. We can add properties to functions "secretly". For example, we define the function Ball here and add the attribute callsign.


[Copy to clipboard]CODE:
function Ball() // It may look a little strange, but this statement
{ creates an object called Ball, and you Can } // quote it or increase the attribute
Ball.callSign = "The Ball" as follows as the following, add attributes
Alert (Ball.CallSign) to Ball; // Output "The Ball"

Since function is an object, we can assign a pointer to a function. As 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 sentence will execute myFunction: output "hello"

We can run this function as if the function name has been replaced by the pointer name. So in the above line, the meaning of this line ptr("hello"); and myFunction("hello"); is the same.
Pointers to functions are quite useful in object-oriented programming. For example: When we have multiple objects pointing to the same function (as follows):

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;

object1.sayMyName ("object1"); // Output "object1"
object2.sayMyName("object2"); // Output "object2"
object3.sayMyName("object3"); // Output "object3"



Since only the pointer is saved (and not 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;

ptr1();                                                                                                                                                . r1();                   // Output "New"

PTR2 (); // Output "New"

We can allocate it after the creation of a function, but we need to point to the function object itself, not the pointer to it. In the following example, I will change the contents of myfunction().

Example 6:


[Copy to clipboard]CODE:
function myFunction()
{
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:


[Copy to clipboard]CODE:
function myFunction()
{
alert("Old");
}
var savedFuncion=myFunction;
myFunction=function()
{
alert("New");
};
myFunction(); // Output "New"
savedFuncion(); // Output "Old"



But be careful, examples like the following will not work because another function called myFunctionPtr is created instead of Modify it.

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 within a function. In the following example, I have a function called getHalfOf, and inside 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, you cannot call: getHalfOf.calculate(10), because calculate only exists when the external function (getHalfOf()) is running. This is consistent with our previous discussion (the function will be compiled, but will only be executed when you call it).
You may be thinking about naming conflicts.For example, which of the following functions called calculate will be called?

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 will first search the local memory address, so it The built-in calculate function will be used. If we delete the inline (local) calculate function, this code will use the global calculate function.

Function: data types and constructors

Let’s take a look at another special feature of functions - which makes them completely different from other object types. A function can be used as a blueprint for a data type. This feature is often used in object-oriented programming to simulate user-defined data types. Objects created using user-defined data types are usually called 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, I created a new data type called Ball.

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 now an object

In this way, ball0=new Ball() has done What? The new keyword creates a new object of type Object (called ball0). It will then execute Ball() and pass this reference to ball0 (for the calling object). Below, you'll see this message: "creating new Ball" if Ball() is actually run.

Example DT2


[Copy to clipboard]CODE:
function Ball(message)
{
alert(message);
}
var ball0=new Ball("creating new Ball"); // Create object and output message
ball0.name="ball-0"; // ball0 now has an attribute: name
alert(ball0. name);                                                   // Output "ball-0"

We can think of line 6 of the above code as an abbreviation of lines 6-8 of the code below:


[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"; name); 

This line of code ball0.construct=Ball has the same syntax as ptr=myFunction in Example 4.
If you still don’t understand the meaning of this line, go back and review Example 4. NOTE: You might consider running ball0.Ball("...") directly, but it won't work because ball0 doesn't have a property called Ball("...") and it doesn't know what you are doing. Want to do something.
When we create an object using the keyword new as above, a new Object is created. We can add properties to this object after creation (just like I added the property name above). The next problem is that if we create another instance of this object, we have to add this to the new object again as below property.)

Example DT3 (creates 3 ball objects)


[Copy to clipboard]CODE:
function Ball()
{
}
var ball0=new Ball(); // ball0 now points to a new instance of 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, which may cause problems in a formal program. Is there any good way to automatically add attributes? Well, there is one: use the this keyword. The word this has a special meaning in function. It points to the object that called the function. Let's look at another example below, this time we add these properties in the constructor:

Example DT4


[Copy to clipboard]CODE:
function Ball(message, specifiedName)
{
alert(message);
this.name=specifiedName; );
alert(ball0.name); // prints "Soccer Ball"

Please remember: it is the new keyword that ultimately causes the constructor to be executed. 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 becomes ball0.name="Soccer Ball".
It mainly means: add attribute name to ball0, and the attribute value is Soccer Ball.
We now just add a name attribute to ball0, which looks very similar to what we did in the previous example, but is a better and more extensible method. Now, we can create as many balls with properties as we want without having to add them manually. Moreover, people also hope that the created Ball object can clearly understand its constructor and can easily find all the properties of the Ball. Let's add more properties to Ball.

Example DT5


[Copy to clipboard]CODE:
function Ball(color, specifiedName, owner, weight)
{
this.name=specifiedName ; ", "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); Soccer Ball"
alert(balloon.name); // Output "Balloon"
alert(ball2.weight); // Output "55"

Hey! Using object-oriented terminology, you can say that Ball is an object type with the following properties: name, color, owner, weight.
We are not limited to adding simple data types such as strings or numbers as attributes. We can also assign objects to properties.Below, supervisor is an attribute of Employee.

Example DT6


[Copy to clipboard]CODE:
function Employee(name, salary, mySupervisor)
{
this.name=name;
this.salary=salary;
this.supervisor=mySupervisor; 🎜>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 example above, both manager and teamLeader have a supervisor property, and this property is an object of type Employee.
Any type of object can be used as an attribute. Recall the previous Example 4 (not Example DT4), a function is also an object. So you can make a function a property of an object. Below, I will add two functions getSalary and addSalary.

Example DT7


[Copy to clipboard]CODE:
function Employee(name, salary)
{
this.name=name; this.salary=salary;

this.addSalary=addSalaryFunction;

this.getSalary=function()
{
return this.salary;
            };
}
function addSalaryFunction(addition)
{
this.salary=this.salary addition;
}

var boss=new Employee("John", 200000); boss.addsalary (10000); // boss grows 10K wages ... Why can the boss's salary grow so much: '(
Alert (boss.getsalarly ()); // Output 210K ... why the default salary also also So high... :'(

AddSalary and getSalary demonstrate several different ways of assigning functions to properties. If you remember our initial discussion; I discussed three different ways of declaring functions. All Those are all applicable here, but the two shown above are the most common.
Let’s see what the difference is. Next, pay attention to the code in lines 9-12. When this part of the code is executed, the function getSalary is executed. Declaration. As mentioned several times before, the result of a function declaration is that an object is created, so the boss is created (the next line 19), and there is a getSalary attribute in the boss.
[Copy to clipboard]CODE:
function Employee(name, salary)
{
this.name=name; addSalary=addSalaryFunction;

this.getSalary=function()
                                                                                                                                            🎜>}
function addSalaryFunction(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 more instances of this object (boss2 and boss3), each instance has a getSalary code A separate copy; in contrast, addSalary points to the same place (ie addSalaryFunction). ​

Look at the code below to understand what is described above.

Example DT8


[Copy to clipboard]CODE:
function Employee(name, salary)
{
this.name=name; this.salary=salary;

this.addSalary=addSalaryFunction;
this.getSalary=function()
                   };
}
function addSalaryFunction(addition)
{
this.salary=this.salary addition;
}

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 Point to the same function object, then
// Both the above outputs should 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, (Ziwu's note: the original text is not pointing to the same function, suspected to be a typo)
// When one of them is modified, it will affect all instances (so both output "boss2").


Maybe not important thing, but here are some conclusions about running a built-in function like getSalary above: 1) More storage space is needed to store the object (because each object instance will have its own copy of the getSalary code); 2) javascript More time is needed 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;

this.addSalary=addSalaryFunction;
this.getSalary=getSalaryFunction;
}
function getSalaryFunction()
{
return this.salary;
}

function addSalaryFunction(addition)
{
this.salary=this.salary addition;
}

Look here, both functions point to the same A place where this will save space and shorten construction time (especially if you have a lot of nested functions in a constructor). There is another function that can improve this design, it is called prototype, and we will discuss it in the next section.

Function: Prototype
Each constructor has an attribute called prototype (prototype, which will not be translated below, use its original text). This attribute is very useful for declaring common variables or functions for a specific class.

You don’t need to explicitly declare a prototype attribute because it exists in every constructor. You can take a 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 properties to it. Properties you add to the prototype will become common to objects 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; in order 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 some fish:


[Copy to clipboard]CODE:
var fish1=new Fish("mackarel", "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{ var fish=eval("fish" i); // I just get the pointer to the fish
alert (fish.name "," fish.color "," fish.livesIn "," fish.price);
}

The output should be:


[Copy to clipboard]CODE:
"makarel, gray, water, 20"
"goldfish, orange, water, 20"
"salmon, white water, 20"

You see all Fish all have attributes livesIn and price, and we don't even declare these attributes specifically for each different fish. This is because when an object is created, this constructor will assign its attribute prototype to the internal attribute __proto__ of the new object. This __proto__ is used by this object to find its properties.
You can also add common functions to all objects through prototype. This has the advantage that you don't need to create and initialize this function every time you construct an object.이를 설명하기 위해 예제 DT9를 다시 방문하여 프로토타입을 사용하여 다시 작성해 보겠습니다.

예제 PT3


[클립보드에 복사]CODE:
function Employee( 이름, 급여)
{
this.name=name; return this.salary;

Employee.prototype.addSalary=function addSalaryFunction(addition)
{
this.salary=this. 급여 추가
}

평소와 같이 객체를 생성할 수 있습니다:


[클립보드에 복사]CODE:
var boss1=new Employee("Joan", 200000 );
var boss2=new Employee ("Kim", 100000);
var boss3=new Employee("Sam", 150000)

 그리고 확인하세요:


[클립보드에 복사]CODE:
alert(boss1.getSalary()); // 출력 200000
alert(boss2.getSalary()) // 출력 100000
alert(boss3.getSalary ()); // 출력 150000

다음은 프로토타입의 작동 방식을 보여주는 다이어그램입니다. 이 객체의 각 인스턴스(boss1, boss2, boss3)에는 생성자(Employee)의 속성 프로토타입을 가리키는 __proto__라는 내부 속성이 있습니다. getSalary 또는 addSalary를 실행하면 이 객체는 __proto__에서 이 코드를 찾아 실행합니다. 참고하세요: 여기에는 중복된 코드가 없습니다(예제 DT8의 다이어그램과 비교).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn