js高级之函数,回调函数

272 阅读1分钟

1.什么是函数?

  • 实现特定功能的n条语句的封装体
  • 只有函数是可以执行的, 其它类型的数据不能执行.

2. 定义函数的方式?

  • 函数声明 示例如下: function fn1() { console.log('fn1()') }
  • 表达式 示例如下:

var fn2 = function () { console.log('fn2()') }

3. 如何调用函数?(假设有一个函数,名为text)

  • test(): 直接调用
  • obj.test(): 通过对象调用
  • new test(): new调用 *text.apply/call(obj):临时让test成为obj的方法进行调用( obj是一个对象)

4.回调函数

1. 什么函数才是回调函数?
  1. 自行定义的
  2. 没有进行调用
  3. 但最终它执行了(在某个时刻或某个条件下)
2. 常见的回调函数?
  • dom事件回调函数 示例如下:

document.getElementById('btn').onclick = function () { alert(this.innerHTML) }

  • 定时器回调函数 示例如下:

setTimeout(function () { alert('到点了'+this) }, 2000)

  • ajax请求回调函数 示例如下: $(function () { $('button').on('click', function () { $.ajax( { type: 'GET', url: 'http://www.liulongbin.top:3006/api/getbooks', data: { id: 1 }, success: function (res) { console.log(res); } } ) }) })