函数的使用

抽取公共部分形成函数,函数的形式参数不用var关键字

       function funname(形式参数){}

或者

varfunname =function(形式参数){} 此时函数被赋值给了一个变量

<html>
 <head>
  <title>javascript函数1</title>
  <script>
    function sayHello(){
      alert("hello world");
    }
    function sayHelloTo(name,sex){
        if(sex==1){
          alert("你好啊"+name+"先生");
        }else{
          alert("你好啊"+name+"女士");
        }
    }
    //sayHello();
    //sayHelloTo("lsp",0);
    var add=function(a,b){
       alert(a+b);
    }
    var plus=function(a,b){
       alert(a-b);
    }
    //add(2,4);
    var arr=[add,plus];
    //arr[1](5,2);
    function returnAdd(a,b){
         return a+b;
    }
    var result=returnAdd(3,7);
    alert(result);
  </script>
 </head>
 <body>
 </body>
</html>

一种更加简洁的创建函数的方式:定义后马上调用

var tens=(function(x){

      return x*x;

    }(10));

    alert(tens);//打印出100

注:jquery使用这种方式构建

函数可以作为参数或者对象进行传递,比如

 //js创建对象的方式,后面会讲到

var o=new Object();

o.f=myprint;

o.f(arr);//已经作为o对象的方法

<html>
 <head>
  <title>javascript函数2</title>
  <script>
    /*(function(a,b){
          alert(a+b);
    })(3,5);*/
    function add(a,b){
      alert(a+b);
    }
    var obj={};//new Object();
    obj.myadd=add;
    obj.myadd(12,89);
    function insertAdd(xyz){
         xyz(3,5);
    }
    insertAdd(add);
  </script>
 </head>
 <body>
 </body>
</html>

函数可以定义在对象里面

对象创建方式会在后面提到,这里给出基本创建方式。

var calculator={
  ope1:1,
  ope2:2,
  result:0,
add:function(){
this.result=this.ope1+this.ope2
  }
    }
calculator.add();
alert(calculator.result);//这里会打印3

注意:jsthis关键字指代调用此函数的对象,也就是calculator对象

不定实参函数

有时候js函数在定义的时候可以不指定参数列表,  

但是在调用的时候可以传入参数,并且函数内部可  

以通过某个内置属性得到这些参数,这个内置属性

就是:arguments

比如定义函数:

  function getArguments_length(){
      return arguments.length;
  }
varargumentsLength= getArguments_length(1,2,3)
  alert(argumentsLength);//打印3

注:从这里可以看出,js函数也相当于一种特殊的对象,拥有一些自己的属性