JS函数基础

一.函数

1.函数是什么

  • 具有特定功能的n条语句的封装体。
  • 只有函数是可执行的,其它类型的数据是不可执行的。
  • 函数也是对象。

2.为什么要用函数

  • 提高代码复用
  • 便于阅读和交流

3.如何定义函数

  • 函数声明
  • 表达式
1   function fun1(){
2     console.log("函数声明定义函数");
3   }
4 
5   var fun2 = function(){
6     console.log("表达式定义函数")
7   }

 

4.如何调用函数

  • test()
  • new test()
  • obj.test()
  • test.call(objx)/test.apply(objx)
 1   function fun(){
 2     console.log("fun执行");
 3   }
 4 
 5   //1.函数自调用,相当于window.fun()调用方式
 6   fun();
 7 
 8   //2.回调函数:事件回调,定时器回调
 9   document.getElementById("btn").onclick = function(){
10     console.log("事件回调");
11   }
12 
13   setTimeout(function(){
14     console.log("定时器回调");
15   },1000);
16 
17   //3.构造函数:实例化对象调用(this指向当前构造函数的实例对象)
18   function Person(name,age){
19     this.name = name;
20     this.age = age;
21   }
22 
23   var person1 = new Person('小红',17);
24 
25   //4.call,apply强制绑定this
26   var obj1 = {name:"obj1"};
27   function fun2(){
28     console.log(this);//用于输出当前this所绑定的对象
29   }
30 
31   fun2();  //this = window
32   fun2.call(obj1);  //this = Object {name: "obj1"}
33   fun2.apply(obj1); //this = Object {name: "obj1"}

5.回调函数

(1)什么函数是回调函数

  • 你定义的
  • 你没有直接执行
  • 最终他执行了(在特定条件下)

(2)常见的回调函数

  • DOM事件函数
  • 定时器函数
  • ajax回调函数
  • 生命周期回调函数
1   document.getElementById("btn").onclick = function(){
2     console.log("DOM事件回调");
3   }
4 
5   setTimeout(function(){
6     console.log("定时器回调");
7   },1000);

6.IIFE

全称: Immediately-Invoked Function Expression 

别名:函数自调用,立即执行函数,IIFE

特点:

  • 只执行一次
  • 代码执行到函数是,此函数就执行了
  • 函数的数据是私有的

7.this

  •  this是关键字,不能用来定义对象
  • this本身是一个内置的变量,该变量指向一个对象
  • this有两种:
    • 全局this:指向window
    • 局部(函数)this:指向它的调用者(例如:构造函数的this指向实例对象)
  • 特殊this:call,apply强制修改this
 1 function fun1(){
 2   
 3   console.log("外部fun1:");
 4   console.log(this);
 5   this.name = "小红";
 6 
 7 }
 8 
 9 var obj = {
10   fun2: function(){
11     console.log("内部fun2:");
12     console.log(this);
13   }
14 }
15 
16 window.fun1(); // this = window
17 new fun1();   // this = 实例对象(fun1{})
18 fun1.call(obj); //this = obj

 

注:使用new 操作符执行步骤:

语法:new fun1();

  1. 创建空对象
  2. 执行函数
  3. 确认this指向
  4. 返回执行结果:fun1{} 给空对象 

此图可以看出new fun1();首先创建一个空对象去指向这个fun1,再给予this的name属性创建并赋值。

 

posted @ 2019-12-06 17:38  All_just_for_fun  阅读(343)  评论(0编辑  收藏  举报