function test(){
console.log(this);//打印的是window
}
window.test();//简写test()
2.2函数作为某个对象的方法时,this指向的是当前对象
let obj = {
name:"test",
show:function(){
console.log(this);//这个打印出来的是window
}
}
let a = obj.show;//a就是function(){console.log(this);}
a();//window.a();
let obj={
name:'hello',
age:19,
show:function(x,y){
console.log(this);//Object
console.log(this.name);//张三
console.log(this.age+x+y);//50
}
}
let obj2={
name:'张三',
age:30
}
obj.show.call(obj2,10,10);
5.2 apply()
let obj={
name:'hello',
age:19,
show:function(x,y){
console.log(this);//Object
console.log(this.name);//张三
console.log(this.age+x+y);//60
}
}
let obj2={
name:'张三',
age:30
}
obj.show.apply(obj2,[10,20]);
es5中bind()
let obj={
name:'hello',
age:19,
show:function(x,y){
console.log(this);//Object
console.log(this.name);//张三
console.log(this.age+x+y);//60
}
}
let obj2={
name:'张三',
age:30
}
let test = obj.show.bind(obj2);
test(10,20);