call 和 apply都能改变函数的this指向
要改变指向的函数.call('当前函数的this',传入的值)
要改变指向的函数.apply('当前函数的this',[传入的值])
apply传入的值写在一个数组里[argument]
function say(name){
var name = 'ls'
console.log(this.name)
console.log('say'+this.name)
this.eat()
}var a = {
name:'zs',
run:function(){
say.call(this,this.name)
},
eat:function(){
console.log('我饿了')
}
}
a.run();
结果为:
zs
sayzs
我饿了
原本say函数中的this指向的应该是window, 在a.eat()中通过call改变this的指向为 a的this 所以say中的this.name为zs
在say函数中通过this调用的变量和函数都应该是a下的变量和方法