JavaScript基础 函数

来源:互联网 发布:mac打开隐藏文件命令 编辑:程序博客网 时间:2024/06/01 15:48
函数
1、函数的定义
   它只定义一次,可能执行或调用多次;
2、定义的方式
   (1)函数声明方式
     function fn(){
        console.log('this is text');
     }  
    (2)字面量方式
      var str=function fn(){
         consol .log('this is text');
    }
3、函数调用
   function fn(){
      console.log('this is text');
   }    
   fn();//输出字符串this is text
4、函数的参数
   (1)形参:出现在函数定义方法中的参数,简称形参;简单的说就是定义函数时使用的参数
   (2)实参:函数调用时实际传入的参数是函数的实际参数,简称实参;简单的说,就是调用函数时使用的参数
    例:function fn(one,two){
            console.log(one +two );
        }
        fn(1,2);//输出3
      上述代码中,定义函数fn时,one,two就是函数的形参,调用fn时one,two就是函数的实参
5、return语句
    函数还可以包含一个返回语句return,尽量定义在函数的最后面,如果定义的代码在return语句之后,不会被执行
    var fu =function(){
      var a=100;  
      return a;
      console.log(fn);
    }
    fn();
    console.log(fn());
    注意:return默认情况下返回的是undefined
6、预定义函数:又称全局函数,允许直接使用
    eval();
       var js="console.log('this is javascript')";
       eval(js);
    isNaN();
    parseInt();
    parseFloat();
        console.log(isNaN(parseInt('123.23'));
    decodeURI();
    encodeURI();
        var uri = "http://www.atguigu.com/Web前端开发工程师";
        var encode = encodeURI( uri );
        console.log( encode );

        var decode = decodeURI( encode );// 输出 http://www.atguigu.com/Web前端开发工程师
        console.log( decode );
7、作用域
    变量和函数都具有作用域,作用域就是变量和函数的可访问的范围,控制着变量和函数的可见性和生命周期
    (1)全局变量:在所有函数之外声明的变量
       var msg='this is text';//定义全局变量msg
       console.log(msg);      //在全局作用域访问变量msg
       function fn(){
          console.log(msg);   //在函数作用域访问变量, this is text
       }
       fn();
    (2)局部变量:在函数内部声明的变量,它只能在该函数内部访问
       function fn (){
          var str ='this is text';  //定义局部变量str
          console.log(str);         //在函数作用域访问  this is text
       }
       fn();
       console.log(str); //出错  在全局作用访问变量str
8、声明提前
   (1)全局变量
    var str;
    console.log(str);  //undefined
    str='this is text';
    console.log(str);  //this is text
   
   (2)局部变量
    function(){
      console.log (str); //undefined
      var str ='this is text';
      console.log (str);  //this is text
    }
    fn();
    console.log(str);   //报错
        
9、函数的作用域
    (1)全局函数
      function fn(str1,str2){
         console.log(str1+str2);
      }    
      fn(1,2);
    (2)内部函数
      function fn(){     //全局函数
         function fun(){ //内部函数
           console.log('fun');
         }
         fun();    //调用正常
      }
      fun();   //报错