this回顾
+ 事件处理函数中this -> 事件源
+ 普通函数中this -> window
+ 定时器this -> window
+ 自调用函数 this -> window
+ 对象Object方法中this -> 当前对象-> 调用该方法的引用变量指向的对象
函数方法call方法
函数名.call(this指向的新对象,参数1,参数2...)
对象方法.call(this指向的新对象,参数1,参数2...)
apply方法
函数名.apply(this指向新对象,[参数1,参数2...])
对象方法.apply(this指向新对象,[参数1,参数2...])
bind方法
var 新函数 = 函数名.bind(this指向新对象)
var 新函数 = 对象方法.bind(this指向新对象)
新函数(参数1,参数2)
案例1
<script>
var obj = {
name: 'jack'
}
var btn = document.querySelector('button')
btn.addEventListener('click', function () {
console.log('this -> ', this)
})
function fun(m,n){
console.log('m ',m, ' n ',n);
console.log('this -> ',this)
}
fun.call(obj,10,20)
fun.apply(obj,[10,20])
var newFun = fun.bind(obj)
newFun(10,20)
</script>
案例2
<script>
var obj1 = {
name:'rose'
}
var obj = {
name:'jack',
say:function(){
console.log('this -> ',this)
}
}
obj.say.call(obj1)
</script>