①普通函数------this指向调用者

1
2
3
4
5
function  fn () {
 
console.log( this) ;}
 
window.fn();

  

②构造函数------指向当前实例对象

1
2
3
4
5
6
7
8
9
function Person (uname, age) {
 
      this.uname = uname;
 
      this.age = age;
 
      console.log(this);
 
    }

  

③方法------指向调用者(非严格模式)

看方法名前面是否有“.”,有的话,“.”前面是谁this就是谁,没有的话this是undefined

④事件处理程序------调用者(定时器)

1
2
3
4
5
window.setInterval(function () {
 
      console.log(this); //window
 
    }, 1000);

  

④自执行函数------window、调用者(非严格模式下)

自执行函数中的this永远是undefined(在严格模式下)

1
2
3
4
5
(function () {
 
      console.log(this);
 
    })();

  

24.改变this指向

call、apply、bind:都是函数的方法

call和apply:都会使函数执行,但是参数不同

bind:不会使函数执行,参数同call

call:函数.call(this, arg1, arg2......);

①call 方法能够在调用函数的同时指定 this 的值

②使用 call 方法调用函数时,第1个参数为 this 指定的值

③call 方法的其余参数会依次自动传入函数做为函数的参数

 

 

apply:函数.apply(this, [arg1, arg2......]);

①apply 方法能够在调用函数的同时指定 this 的值

②使用 apply 方法调用函数时,第1个参数为 this 指定的值

apply 方法第2个参数为数组,数组的单元值依次自动传入函数作为函数的参数

 

 

 

通过apply改变this指向

bind:函数.bind(this, arg1, arg2......);

bind,用于既想要改变this的指向,但是又不希望立刻执行函数