1.call()方法
作用:立即调用函数并改变this指向
应用场景:经常用于继承属性/方法
function Father(uname, age, sex) {
this.uname = uname
this.age = age
this.sex = sex
}
function Son(uname, age, sex) {
Father.call(this, uname, age, sex)
}
let son = new Son('刘德华', 18, '男')
console.log(son);
2.apply()方法
作用:立即调用函数并改变this指向
应用场景:搭配内置对象使用效果更佳
和call()不同的地方是参数二必须是数组,打印的是字符串
let o = {
name: 'john'
}
function fn(arr) {
console.log(this);
console.log(arr);
}
fn.apply(o, ['pink']) //参数二必须传递数组
// apply的其他应用 搭配其他内置对象使用
let arr1 = [1, 33, 44, 55]
let max = Math.max.apply(Math, arr1) //第一个参数不要传null
console.log(max);
3.bind()方法
作用:改变this指向但不会立即调用函数,返回由指定的this值和初始化参数改造的原函数拷贝,看起来很鸡肋但实际开发用的很多
应用场景:某些场景下搭配定时器使用,比如我们需要点击一个按钮后立马禁用并在3秒后移除禁用
let a = {
name: 'lihuan'
}
function fn1(a, b) {
console.log(this);
console.log(a + b);
}
// fn.bind(o) //不打印
let f = fn1.bind(a, 1, 2) //要用另一个方法去接收
f();
// bind的作用是:如果有的函数不需要立即调用,又想改变this的指向,例如:按钮 点击后3秒开启禁用
btn.onclick = function() {
this.disabled = true
setTimeout(function() {
this.disabled = false //定时器指向window
}.bind(this), 3000) //在定时器的函数外面绑定bind,倒计时结束生效,外面的this也是指向btn,this不会有任何变化,写活了
}