在学习javascript的过程中发现this指针很有趣,就简单研究了一下。
话不多说,先来段简单的代码:
function a(){
console.log(this);
}
// a();//全局方法a()属于Window对象
var obj1={
name: 'zs',
age: 20,
say: function(msg){
console.log(this+msg);
}
}
// obj1.say();//say()方法属于对象obj1;
setTimeout(function(){
console.log(this);//定时器属于Window对象
},10)
- 改变this指向有三个方法 call,apply,bind
var obj2={
name: 'xiaowu',
age: 35,
say: function(msg1,msg2,msg3){
console.log(this+msg1+msg2+msg3);
}
}
- call & apply & bind 首个参数都是this的实际指向,后面是传入的实际参数
- bind更改this指向但不调用,call & apply 更改指向后立即调用
- apply 的 参数以数组形式传入,call & bind 的参数是逐个传入
obj2.say.call(obj1.name,' is',' a',' boy!');
obj2.say.apply(obj1.name,[' is',' a',' girl!']);
obj2.say.bind(obj1,' is',' a',' dog!');
setTimeout((function(msg1,msg2,msg3){
console.log(this);
console.log(msg1,msg2,msg3);
}).bind(obj1,' is',' a',' dog!'),50);//定时器本身就是对定义的方法的延时调用