1.回调函数
<script>
function f(n) {
console.log('n=' + n)
}
function fn(a, cb) {
let num = 10
num += a
// 调用函数cb
cb(num)
}
fn(20, f)
</script>
2.函数的返回值
<script>
let object = { id: 1 }
function fn() {
console.log(this) //?
let num = 20
let f = function () {
console.log(this) // window
console.log(num) // 20
}
f()
return f
}
// let rt = fn()
// rt()
// call调用函数
let rt1 = fn.call(object) // object调用fn函数
rt1()
</script>
3.函数的作用域
call apply bind三者的区别:
1、相同点
调用函数,修改函数的this指向的方法,call apply bind三者都是Function原型对象的方法
2、不同点
2-1 call和apply可以直接调用函数,bind是返回一个函数,并没有执行函数
2-2 call的参数使用,割开,apply传递的参数使用数组
2-3 bind参数和call类型
<script>
// var a // 预解析 变量提示 作用域提升
// console.log(a) // undefined
{
//console.log(a) // 暂时性死区(tdz)
var a = 10
let b = 20 // let const 没有变量提升过程
}
//console.log(a) // 10
// console.log(b) // 报错 b is not defined
// let fn = new Function('a,b', 'return a+b')
// console.log(fn(1, 2))
let object = { id: 100, n: 20, m: 30 }
function fn(a, b) {
console.log('this.id=', this.id) // 100
this.n = a
this.m = b
return a + b
}
let rt = fn.call(object, object.n, object.m)
// console.log(rt) //50
rt = fn.apply(object, [10, 20])
// console.log(rt, object)
// bind只是返回一个函数,不会直接调用函数
rt = fn.bind(object, 1, 2)
console.log(rt(), object)
</script>
4.函数的链式操作
<script>
// 给元素添加内容
function html(str) {
this.innerHTML = str
return this
}
// 给元素设置样式
function css(key, value) {
this.style[key] = value
return this
}
let box = document.getElementsByClassName('box')[0] // HTMLDivElement
box.html = function (str) {
this.innerHTML = str
return this
}
box.css = function (key, value) {
this.style[key] = value
return this
}
// let rt = html.call(box, 'hello world')
// rt = css.call(rt, 'color', 'red')
// rt = css.call(rt, 'font-size', '20px')
box.html('hello').css('color', 'red').css('border', '1px solid black').html('world').css('color', 'blue')
</script>