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 }
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) )
3 function statement and function literal:
function f(x) { return x * x ;} // var f = function(x){ return x * x ;} //
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) ;} //这样做的好处; 调用自身非常爽。
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);
What happens if we only pass one parameter?
function x(a,b){ document.write(a+ " "+b); } x(1);
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);