主要应用场景
1、apply方法(数组没有max,min方法;可以借助Math对象方法,利用apply传入数组进行数组求最大值最小值)
注意,apply方法中第二个参数传入数组,但在方其他函数(方法)调用apply时,传入调用函数(方法)的值为字符串格式
function a(x) {
console.log(x);
// 打印x输出为'pink'
}
var arr = ['pink']
// appl第二个参数传入值为数组['pink']
a.apply(null, ['pink']);
3、bind方法(返回值为改造后的函数拷贝,不需要立即执行时使用)
这里使用let 利用let的块级作用域也可以;使用箭头函数也可以,箭头函数内的this指向上一层
var btn = document.querySelector('button')
btn.onclick = function () {
this.disabled = true
setTimeout(function () {
this.disabled = false
console.log('can click')
}.bind(this)给定时器函数添加bind方法,这里的this在定时器函数外:指向btn, 3000)
}
var btn = document.querySelector('button')
btn.onclick = function () {
this.disabled = true
setTimeout(() => {
this.disabled = false
// 实际上箭头函数里并没有 this,如果你在箭头函数里看到 this,你直接把它当作箭头函数外面的 this 即可。外面的 this 是什么,箭头函数里面的 this 就还是什么,因为箭头函数本身不支持 this。有人说「箭头函数里面的 this 指向箭头函数外面的 this」,这很傻,因为箭头函数内外 this 就是同一个东西,并不存在什么指向不指向。
console.log('can click')
}, 3000)
}