call,apply,this指向

每个函数都包含两个非继承而来的方法call()和apply(),这两个方法都是在特定的作用域中调用函数,等于设置函数体内this对象的值。

apply()方法接收两个参数:
第一个:指当前对象,也就是正在调用这个函数的对象
第二个:数组,例:fn.apply(this, ["name", "jeck"]);或数组对象,例:fn.apply(this, new Array("name", "jeck"));或arguments对象

call()方法接收两个参数:
第一个:指当前对象,也就是正在调用这个函数的对象
第二个:参数列表,例:fn.call(this, num1, num2, num3);

🌰://call方法,可以改变this的指向,this写在括号中

 var a={
   name:"小米",
   eat:function(num,num1){
   console.log("eat"+num+num1,this)
  }
}
 var b ={name:"app"};
 a.eat.call(b);//this指向b
 a.eat.call(red);//this指向red
 a.eat.call(this);//this指向window
 a.eat.call()//this指向window
 a.eat.call(b,"香蕉","菠萝");//函数带有参数的时候,把this写在参数的后面

//apply:同call,区别:带有参数时传的是数组 
a.eat.apply(b,["栗子","冬瓜"]);

this的指向
1.谁调用的方法,this就指向谁

function test(){
  console.log("test方法");
  return function(){
  console.log("哈哈哈哈")
  }
 }
 console.log(window.test,this);//this指window

2.直接调用方法,this指向window
给red添加点击事件

①red.onclick=test();//返回值
②red.onclick=test;//执行点击方法的时候调用了test
red.onclick();//this指向red
test()//this指向window

3、定时器里的this指向window;

 function test(){
  var _this = this;//下划线this是red
  setTimeout(function(){
    console.log("test方法",_this);
},1000)

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容