咨询电话:
15628812133
13
2017/05

JS中精选this关键字的指向规律你了解吗?

发布时间:2017-05-13 17:58:29
发布者:jiangbing
浏览量:
0

一、首先要明确:

1、谁最终调用函数,this指向谁。

2、this指向的永远只可能是对象!

3、this指向谁永远不取决于this写在哪,而取决于函数在哪里调用!

4、this指向的对象,我们称之为函数的上下文context,也叫做函数的调用者是谁!

二、this指向的规律(与函数调用的方式息息相关)

this指向的情况取决于函数调用的方式有哪些(总结如下):

1、通过函数名()直接调用--this 指向window;

function func(){
         console.log(this);
         }
func();

2、通过对象.函数名()调用的--this指向这个对象

狭义对象: this指向--obj

var obj={
      name:"obj",
      func1:func
     };
     obj.func1();

 广义对象: this指向--div

 document.getElementById("div").onclick=function(){this.style.backgroundColor="red";}

3、this指向——数组arr

var arr=[func,1,2,3];
     arr[0]();

4、函数作为window内置函数的回调函数调用,this指向window setInterval,setTimout等

setInterval(func,1000);         
setTimeout(func,1000)

5、函数作为构造函数,用new关键字调用时:this指向新定义的对象obj

 var obj=new func();

6、通过call、apply、bind调用,this指向我们规定的对象。

Func.call(obj,参数一,参数2,参数3.。。。)

Func.allply(obj,[ 参数一,参数2,参数3.。。。])

Func.bind(obj)( 参数一,参数2,参数3)   var f = func.bind(obj).   f(…….);


关键词:
返回列表