What is the function of
a function is a set of statements to complete a specific function. If no function, it may be required to complete the task Five, ten lines, and even more code. Then we can accomplish a specific function block of code into a function and directly call this function, we save a lot of trouble to re-enter the code.
How to define a function? The basic syntax is as follows:
function 函数名()
{
函数代码;
}
Description:
-
Keyword function defined functions.
-
"Function" you take a function name.
-
"Function Code" is replaced with a specific function completion code.
Consider the following examples:
var add2;
function add2(){
var sum = 3 + 2;
alert(sum);
}
Function call
JavaScript function call There are four ways:
- As a function call
- As a function of the method call
- Use the constructor function calls
- Call the function as a function method
this keyword
Each different ways that this is initialized.
Generally, in Javascript, the this object refers to the current execution of the function.
(Note that this is a reserved keyword, you can not modify the value of this.)
As a function call
Examples
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // myFunction(10, 2) 返回 20
The above function does not belong to any object. But in JavaScript, it is always the default global object.
The default is the global object in HTML HTML page itself, so the function is part of the HTML page.
Object page in the browser is the browser window (window objects). Over function automatically becomes a function of the window object.
As a function of the method call
Examples
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // 返回 "John Doe"
A method is a function fullName. Function belongs to the object. myObject is the owner of the function.
this object has a JavaScript code. Examples of this value myObject object.
Use the constructor function calls
Examples
// 构造函数:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
// This creates a new object
var x = new myFunction("John","Doe");
x.firstName; // 返回 "John"
Call the constructor will create a new object. The new object inherits the properties and methods of the constructor.
Note:
(this keyword has no value constructor.
Value is created when this function is called to instantiate an object (new object).)
Call the function as a function method
Examples
function myFunction(a, b) {
return a * b;
}
myObject = myFunction.call(myObject, 10, 2); // 返回 20
() Method you can set this value by the call, and the caller as a new method of an object that already exists.