- call
call是一个方法,是函数的方法,call可以调用函数
function fun () {
console.log(this)
}
fun.call()
call可以改变函数中this的指向
let cat = {
name: ‘喵喵‘
}
let dog = {
name: ‘旺旺‘,
sayName: function () {
console.log(‘我的名字是‘ + this.name)
}
}
dog.sayName()
输出结果
dog.sayName.call(cat)
输出结果
通过call传参
let cat = {
name: ‘喵喵‘
}
let dog = {
name: ‘旺旺‘,
sayName: function () {
console.log(‘我的名字是‘ + this.name)
},
eat: function (food) {
console.log(‘我喜欢吃‘ + food)
}
}
dog.sayName.call(cat)
dog.eat(‘骨头‘)
dog.eat.call(cat, ‘鱼‘)
输出结果
- apply
apply和call的区别,call传参是依次往后排,apply传参是传一个数组
let cat = {
name: ‘喵喵‘
}
let dog = {
name: ‘旺旺‘,
sayName: function () {
console.log(‘我的名字是‘ + this.name)
},
eat: function (food1, food2) {
console.log(‘我喜欢吃‘ + food1 + food2)
}
}
dog.eat.call(cat, ‘鱼‘, ‘肉‘)
dog.eat.apply(cat, [‘鱼‘, ‘肉‘])
- bind
bind不会调用函数,会返回一个函数,传参格式跟call一样
let cat = {
name: ‘喵喵‘
}
let dog = {
name: ‘旺旺‘,
sayName: function () {
console.log(‘我的名字是‘ + this.name)
},
eat: function (food1, food2) {
console.log(‘我喜欢吃‘ + food1 + food2)
}
}
dog.eat.call(cat, ‘鱼‘, ‘肉‘)
dog.eat.apply(cat, [‘鱼‘, ‘肉‘])
let fun = dog.eat.bind(cat, ‘鱼‘, ‘肉‘)
fun()