JS-函数

目录

1.函数介绍

函数的作用:

2.函数声明

    函数声明与提升

3.函数内部属性

  3.1arguments

    3.2this

 4.IIFE

作用

5.作用域

6.函数调用 修改this指向

 1.如何修改函数this指向?    (1)call(执行环境对象,实参列表)    (2)apply(执行环境对象,[实参列表])    (3)bind(执行环境对象,实际参数)(实际参数) 2.函数调用得方式   (1)函数名()  (2)call();  (3)apply()  (4)bind()()

7.函数应用(回调函数)

回调函数的作用

8.闭包


1.函数介绍

函数允许我们封装一系列代码来完成特定任务。当想要完成某一任务时,只需要调用相应的代码即可。方法(method)一般为定义在对象中的函数。

JavaScript 使用关键字 function 定义函数。

函数可以通过声明定义,也可以是一个表达式。

函数的作用

功能的封装,直接调用,代码复用率提高

构建对象的模板(构造函数)

函数实际上是对象,每个函数都是Function类型的实例,并且都与其他引用类型一样具有属性和方法,由于函数是对象,因此函数名实际上也是一个指向函数对象的指针,不会与某个函数绑定。

2.函数声明

函数声明(使用function关键字)格式:

function 函数名(形参列表){
    //函数体
}

函数表达式格式:

var 函数名 = function(形参列表){
    //函数体
}

    函数声明与提升

/**
 * 1.函数声明 
 * 函数体执行到return结束 没写return 执行到}结束 return 后面不写代码
 */
function add(a,b,c){
	console.log(a+b,c);//3 undefined
	// 函数内部不写返回值 返回undefined 
	return a + b;
	// 一般情况下 写在return后面代码不生效  
    //变量提升---函数提升到作用域最前方 var声明变量提升到作用域前方
	var c = 10;
	console.log(a + b );
}
// var result = add(1,2,10);
var result = add(1,2);
console.log(result);//3

运行结果:
3 undefined
3
--------------------------------------------------------------------------

/**
 * 2.函数表达式 匿名函数赋值给一个变量
 */
var sum = function(a,b){
	console.log(a+b);//3
}
sum(1,2,3,4,5)

运行结果:
3

/**
 * 函数提升 函数会提升到当前作用域得最顶部 var声明变量会提升到当前作用域顶部
 */

foo();
function foo(){
	console.log('我是一个函数');
}
var foo = 'hello function';
console.log(foo);

运行结果:
我是一个函数
hello function

3.函数内部属性

  3.1arguments

arguments是一个类数组对象,包含着传入函数中的所有参数。arguments主要用途是保存函数参数,但是这个对象还有一个名为callee的属性,该属性是一个指针,指向拥有这个arguments对象的函数。

callee属性是 arguments 对象的一个成员,仅当相关函数正在执行时才可用。

callee 属性的初始值就是正被执行的Function对象。

/**
 * auguments 属性 专门用来保存实际参数列表得类数组对象 
 * arguments内部属性 callee  仅当当前相关函数正在执行才可用
 */
function fn(a,b){
	console.log(a,b);
	console.log(arguments.length);
	console.log(arguments[3]); 
	console.log(arguments.callee,'arguments得属性')
	console.log(arguments.callee === fn)
	/**
	 * 面试题:如何将类数组对象转为数组对象 
	 * 1.Array.from() 将类数组转为数组
	 * 2.使用拓展运算符 
	 */
	console.log(Array.from(arguments));
	console.log([...arguments]);
}
fn(1,2,3,4,5);
// 形参个数就是函数得长度
console.log(fn.length);

运行结果:
1 2
5
4
[Function: fn] arguments得属性
true
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]
2

     使用arguments.callee 实现递归

/**
 * 递归 使用arguments.callee 实现递归 
 */
function fc(n){
	if(n==1){
		return n = 1
	}
	return arguments.callee(n-1) * n
}
console.log(fc(10));//1*2*...*10

运行结果:
3628800

     使用递归实现斐波那契数列 0 1 1 2 3 5 8 13 21 34 55

/**
 * 斐波那契数列 0 1 1 2 3 5 8 13 21 34 55 
 * 使用递归实现
 * 1 1  f(1) 1  f(0) 0 前两项相加之和等于第三项 
 * 0 0 	
 * 2 1	f(2) = f(1) + f(0) = 1 + 0 = 1
 * 3 2	f(3) = f(1) + f(2) = 1 + 1 =2
 */
function fb(n){
 if(n<=1){
 	return n
 }
	return arguments.callee(n-1) + arguments.callee(n-2) 
}
console.log(fb(10));

运行结果:
55

    3.2this

/**
 * this 是函数赖以执行得环境对象
 * 	1.关注this被谁拥有  2.关注拥有this方法被谁调用  this就指向谁
 * 1.单独使用this  this在nodejs指向当前模块 this在浏览器指向全局对象window
 * 2.函数内部使用this  this指向全局对象 global window
 * 3.方法中使用this  this指向拥有该方法得调用者 
 * 4.在事件中使用this  this指向接收事件得元素
 * 5.显示函数绑定时,可以更改this指向
 */
// console.log(this);//{} 当前模块 
// function foo(){
// 	console.log(this);//全局对象global obejct 
// }
// foo()
name = 'larry';
var obj = {
	name:'terry',
	sayName:function(){
		console.log(this);
		console.log(this===obj);
		console.log(this===globalThis);
		console.log(this.name);
	}
}
// obj.sayName();//this -->obj对象 this===obj true this.name--->terry
var x = obj.sayName;
x();//this --global this===obj false this===globalThis true 


var obj1 = {
	name:'terry'
}
var obj2 = {
	sayName:function(){
		console.log(this.name,this)
	}
}
// call 方法修改this指向  参数:this执行得环境对象 
obj2.sayName.call(obj1);
//显示函数绑定时,可以更改this指向
-----------------------------------------------------------------
运行结果:
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  queueMicrotask: [Function: queueMicrotask],
  performance: Performance {
    nodeTiming: PerformanceNodeTiming {
      name: 'node',
      entryType: 'node',
      startTime: 0,
      duration: 46.9070999622345,
      nodeStart: 1.1121997833251953,
      v8Start: 4.446199893951416,
      bootstrapComplete: 33.76839995384216,
      environment: 16.089199781417847,
      loopStart: -1,
      loopExit: -1,
      idleTime: 0
    },
    timeOrigin: 1687853223141.992
  },
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  name: 'larry'
}
false
true
larry
terry { name: 'terry' }

 this指向.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<button id="btn">点击我</button>
	<script>
		console.log(this,'this指向全局对象window对象');//函数内部使用,指向全局对象
		/**
		 * 点击按钮获取this 
		*/
		// 1.获取按钮
		var btn = document.getElementById('btn');
		console.log(btn);
		// 2.给按钮绑定事件 on事件类型  查看this指向 
		btn.onclick = function(){
			console.log(this)
		}
	</script>
</body>
</html>

 

 4.IIFE

IIFE: Immediately Invoked Function Expression,意为立即调用的函数表达式,也就是说,声明函数的同时立即调用这个函数。

作用

  • 页面加载完成后只执行一次的设置函数。

  • 将设置函数中的变量包裹在局部作用域中,不会泄露成全局变量。

    /**
     * 立即执行函数  声明得时候就调用 
     * 特点:1.页面加载得时候会立即执行一次 
     *      2.拥有局部作用域 变量不会泄露
     */
     var a = function(b,c){
     	return b + c
     }
     console.log(a(1,2));;
    运行结果:
    3
    --------------------------------------------------------------
    
    /**
     * 立即执行函数 (匿名函数(形式参数){})(实际参数)
     */
     (function(a,b){
     	console.log('我是立即执行函数',a,b)
     })(1,2)
    运行结果:
    我是立即执行函数 1 2
    --------------------------------------------------------------
     
    var res = ((function(a){
     	console.log('我是立即执行函数2',a)
     })('hello'));
     console.log(res);
     var i = 0;
     for(;i<6;i++){
     	function foo(){
     		console.log(i)
     	}
     }
     foo();//6
    运行结果:
    我是立即执行函数2 hello
    undefined
    6
    ---------------------------------------------------------------
    
     for(var i = 0;i<6;i++){
     	(function(j){
     		console.log(j)
     	})(i);//0 1 2 3 4 5
     }
    运行结果:
    0
    1
    2
    3
    4
    5
    ---------------------------------------------------------------
    
     var arr = [];
     // 循环遍历 往数组添加元素 
     for(var i=0;i<5;i++){
     	// 闭包 函数内部使用函数外部变量  解决作用域问题
     	arr[i] = (function(j){
     		return function(){
     			console.log(j)
     		}
    	})(i);// 0 1 2 3 4 
     }
     arr[4]();
    运行结果:
    4
    -----------------------------------------------------------------
    
    var arr = [];
    for( let i=0;i<5; i++){
    	arr[i] = (function(j){
    		console.log(j)
    })(i)
    }
    arr[4];
    运行结果:
    0
    1
    2
    3
    4

    5.作用域

  • ES5中(ES5中没有块级作用域)

  • 函数作用域: 在 JavaScript函数中声明的变量,会成为函数的局部变量。

    函数内部声明的变量,在函数外部不能访问。

  • 全局作用域:函数之外声明的变量,会成为全局变量。

    函数外部声明的变量,在函数内部可以访问。

    当函数嵌套,在这个时候,内部函数与外部函数的这个变量就组成了闭包。

    /**
     * 块级作用域 if(){} for(){}
     */
    if(true){
    	var a = 10;
    };
    console.log(a);//10
    ------------------------------------------------------
    
    if(true){
    	let a = 10;
    };
    console.log(a);//a is not defined
    ------------------------------------------------------
    
    /**
     * 函数内作用域 (局部作用域) 函数内部得变量函数外部是无法获取 不适用var声明得变量也是全局变量 a = 10;
     * 函数外得作用域 (全局作用域) 函数内部可以获取函数外部得变量
     */
    var v1 = 10;
    v2 = 20;
    function foo(){
    	var a = 30;
    	b = 30;
    	console.log(v1,v2);
    }
    foo();
    //console.log(a,b);//a is not defined
    console.log(b);
    运行结果:
    10 20
    30
    -------------------------------------------------------
    
    var a = 1;
    function foo(){
    	// var a; 
    	console.log(a,'第二次');// undeifned
    	a = 2;
    	console.log(a,'第三次');//2
    	var a = 3;
    	console.log(a,'第四次')//3
    }
    console.log(a,'第一次');//第一行代码 1
    foo();
    console.log(a,'第五次');//1
    运行结果:
    1 第一次
    undefined 第二次
    2 第三次
    3 第四次
    1 第五次
    ----------------------------------------------------------
    
    var a = 10;
    function foo() {
      console.log(a); //undefined
      var a = 100;
      console.log(a); //100
      function fn(){
        console.log(a) ;//undefined
        var a = 200;
        console.log(a);//200
      }
      fn()
    }
    foo()
    运行结果:
    undefined
    100
    undefined
    200

       作用域链

    /**
     * 作用域链:自由变量沿着作用域追层向上寻找的过程构成了作用域链
     * 自由变量:当前作用域中本身没有这个变量,但是想要获取到该变量对应的值 
     */
    var a = 10;
    function foo(){
    	var b = 20;
    	function fn(){
    		var c = 30;
        var d = 40;
    		console.log(a);// 自由变量,顺作用域链向父作用域找 
    		console.log(b);// 自由变量,顺作用域链向父作用域找 
    		console.log(c);// 本作用域的变量
    		console.log(d);// 本作用域的变量
    	}
    	fn()
    }
    foo();
    运行结果:
    10
    20
    30
    40
    
    ---------------------------------------------------------------
    var a = 10;
    function fn() {
      var b = 20;
      function bar() {
        console.log(a + b) 
      }
      return bar
    }
    var x = fn();
    b = 200;
    x();
    运行结果:
    30

    6.函数调用 修改this指向

  •  1.如何修改函数this指向?
        (1)call(执行环境对象,实参列表)
        (2)apply(执行环境对象,[实参列表])
        (3)bind(执行环境对象,实际参数)(实际参数)
     2.函数调用得方式 
      (1)函数名()
      (2)call();
      (3)apply()
      (4)bind()()

  • /**
     * 1.如何修改函数this指向?
    	* 1.call(执行环境对象,实参列表)
    	* 2.apply(执行环境对象,[实参列表])
    	* 3.bind(执行环境对象,实际参数)(实际参数)
     *
     * 2.函数调用得方式 
     * 	1.函数名()
     * 	2.call();
     * 	3.apply()
     * 	4.bind()()
     */
    var obj = {
    	name:'terry',
    	sayName:function(){
    		console.log(this,this.name)
    	}
    }
    var obj1 = {
    	name:"larry",
    	sayName:function(a,b){
    		console.log(this.name,a,b);
    	}
    }
    // obj.sayName();
    // obj1.sayName();
    // 1.修改this指向  call()
    // obj1.sayName.call(obj,1,2);
    // 2.修改this指向  apply()
    // obj1.sayName.apply(obj,[1,2]);
    // 3.修改this指向 bind()() bind()返回当前函数本身 bind()()调用函数
    // console.log(obj1.sayName.bind(obj,1,2));
    obj1.sayName.bind(obj)(1,2);
    
    运行结果:
    terry 1 2

    7.函数应用(回调函数)

  • 回调函数的作用

  • 回调函数一般都用在耗时操作上面:因为主函数不用等待回调函数执行完,可以接着执行自己的代码。比如ajax请求,比如处理文件等。

    /**
     * 1.函数可以作为参数 回调函数 回头调用 主函数先执行  回调函数再执行
     * 2.函数可以作为返回值 
     */
     function foo(x,y,callback){
     	console.log(x,y);
     	callback(3,4)
     }
     function fn(a,b){
     	console.log(a,b)
     	return a + b
     }
     foo(1,2,fn,function(){
     })
    
    运行结果:
    1 2
    3 4
    -------------------------------------------------------------------------
    
     var arr = [1,2,3,4,5];
     Array.prototype.forEach = function(callback){
     	for(var i=0;i<this.length;i++){
     		callback(this[i])
     	}
     }
     arr.forEach(function(item){
     	console.log(item)
     })
    
    运行结果:
    1
    2
    3
    4
    5
    ---------------------------------------------------------------------------
    
     function A(callback){
     	callback();
     	console.log('我是主函数')
     }
     function B(){
     	setTimeout(function(){
     		console.log('我是回调函数')
     	},1000)
     }
     A(B); //js事件循环 nodejs 面试
     setTimeout(function(){
     	console.log(1)
     },0);
     console.log(0);
     console.log(2);
    
    运行结果:
    我是主函数
    0
    2
    1
    我是回调函数
    ----------------------------------------------------------------------
    
     function foo(){
     	var a = 10;
     	return function(){
     		console.log(a)
     	}
     };
     var res = foo();
     console.log(res);
     res();
    
    运行结果:
    [Function (anonymous)]
    10
    ---------------------------------------------------------------------------
    
    var a = 10;
    function fn() {
      var b = 20
      function bar() {
        console.log(a + b)
      }
      return bar
    }
    b = 200;
    var x = fn();
    x();
    运行结果:
    30

    8.闭包

  • 闭包:函数内部作用域可以访问函数外部作用域变量
      词法作用域:内部函数需要访问外部函数中得变量或者方法

  •  产生条件:1.嵌套函数
      2.函数内部存在对函数外部变量引用
      3.变量不会被回收机制回收 缓存变量

  • 优点:不会污染变量 变量会被维持缓存

  • 缺点:造成内存泄漏 造成性能问题 

    /**
     * 闭包:函数内部作用域可以访问函数外部作用域变量
     * 词法作用域:内部函数需要访问外部函数中得变量或者方法
     * 产生条件:1.嵌套函数
     * 2.函数内部存在对函数外部变量引用
     * 3.变量不会被回收机制回收 缓存变量
     * 优点:不会污染变量 变量会被维持缓存
     * 	缺点:造成内存泄漏 造成性能问题 
     */
    
     function func() {
       var a = 1, b = 2;
       function closure() {
         return a + b;
       }
       return closure;
     }
     console.log(func()()); 
    运行结果:
    3
    -----------------------------------------------------------------------
    
    /**
     * 调用一次函数 变量减少一次 
     */
     function foo(){
     	var a = 10;
     	function fn(){
     		a--;
     		console.log(a)
     	}
     	return fn
     }
     var res = foo();
     res();//9
     res();//8
     res();//7
    运行结果:
    9
    8
    7
    ----------------------------------------------------------------------
    
     function sum(){
     	var a = 10;
     	a--;
     	console.log(a)
     }
     sum();9
     sum();9
     sum();9
    运行结果:
    9
    9
    9
    ------------------------------------------------------------------------
    
    function f1() {
      var n = 999;
      nAdd = function () { n += 1 }
      function f2() {
        console.log(n);
      }
      return f2;
    }
    var result = f1();
    result();//999
    nAdd();
    result();//1000
    运行结果:
    999
    1000

    闭包this

  • <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <script>
          var name = "window";
    			console.log(this)
          var obj = {
            name: "obj",
            say: function () {
    					console.log(this.name)
              return function () {
                console.log(this.name);
              };
            },
          };
          var x = obj.say();
          x();
        </script>
      </body>
    </html>
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值