Home > Web Front-end > JS Tutorial > body text

Introduction to Javascript Part 5 js function page 1/2_Basic knowledge

PHP中文网
Release: 2016-05-16 19:03:03
Original
1176 people have browsed it

1, Function:
function is a js code that is defined once but can be called multiple times.
When a function is called by an object, then the function is called a method of the object.

function cssrain( x , y) 
{ 
 //code 
}
Copy after login

Explanation:
cssrain : is the function name;
() : is the operator;
x, y : is the parameter;

2, the return value of the function:

function a(x){ 
    document.write(x); 
} 
function b(y){ 
   document.write(y); 
   return y; 
} 
alert( a(1) )  //因为没写return,所以返回undefined 
alert( b(2) )
Copy after login

3 function statement and function literal:

function f(x) { return x * x  ;}   // 
var f  = function(x){ return  x * x ;}   //
Copy after login

The first one is created by the function statement, The second one is to directly define an expression using a function literal. Of course, in this way, an anonymous function is created.
Although the direct variable can be anonymous, you can also specify a function name;
For example:

var f  = function fact(x){ return  x * fact(x-1) ;}   //这样做的好处; 调用自身非常爽。
Copy after login



4 Function naming:
function like_this(){}
or function likeThis(){} // Camel case

5 Function parameters:
Since js is a loosely typed language, the parameters do not need to specify any data type. Parameters can be more or less,
For example: function x(a,b){} //We wrote 2 parameters
If we pass 3 parameters, js will automatically ignore the extra ones/
Example:

function x(a,b){ 
 document.write(a+ "  "+b); 
}  
x(1,2,3,4);
Copy after login

What happens if we only pass one parameter?

function x(a,b){ 
 document.write(a+ "  "+b); 
}  
x(1);
Copy after login

We found that undefined was output, so js will assign the less to undefined;
This may cause program errors.
Solution:

function x(a,b){ 
var b = b || " ";  // 这个是或运算符,如果前面的b为undefined,也就是false,他会取后面的空字符 
 document.write(a+ "  "+b); 
}  
x(1);
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template