函数
什么是函数 ?
- 实现特点功能的n条语句的封装体
- 只有函数是可以执行的,其它类型的数据不能执行
为什么要用函数 ?
如何定义函数 ?
function fn() {
console.log('fn()')
}
var fn = function () {
console.log('fn()')
}
如何调用(执行)函数 ?
- test():直接调用
- obj.test():通过对象调用
- new test():new调用
- test.call/apply(obj): 临时让test成为obj的方法进行调用
var obj = ()
function test() {
this.xxx = 'test'
}
test.call(obj)
console.log(obj.xxx)
回调函数
什么是回调函数 ?
常见的回调函数 ?
- dom事件回调函数
- 定时器回调函数
- ajax请求回调函数
- 生命周期回调函数
document.getElementById('btn').onclick = function () {
alert(this.innerHtml)
}
setTimeout(function () {
alert('hello')
}, 2000)
setInterval(function() {
console.log('hello')
}, 100)