js/this指向

1、this概述

this是javascript语言的一个关键字,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用,随着函数使用场合的不同,this的值会发生变化,指向是不确定的,也就是说可以动态改变this的指向,但是有一个总的原则,就是this总是指向调用函数的那个对象。(this一般情况下都是指向函数的拥有者)

2、"use strict" 严格模式下this的值是undefined

  function test(){

    "use strict";           // 严格模式

    console.log(this)     // undefined

  }

  test()

3、数组

  function f1(){

    console.log(this)  

  }

  var  arr = [f1,2,3];

  arr[0]()     // this指向arr

  var f2 = arr[0];

  f2();         // this指向window

4、内置函数 setTimeout(定时器中this指向window)

  function f1(){

    console.log(this)  

  }

  setTimeout(f1,1000)    // this指向window

5、回调函数中this也是指向window

6、对象

  var obj = {};

  obj.name = 123;

  obj.action = function(){console.log(this)}

  function  f1(){console.log(this)}

  obj.action()          // this指向obj

  obj.f2 = f1;

  obj.f2()    //this指向obj

7、构造函数中的this

  构造函数就是通过这个函数生成一个实例,当一个函数作为构造函数使用时(通过new关键字),它的this指向新创建的那个对象,如果没有使用new关键字,那么它就是一个普通的函数,this指向window

8、自执行函数中的this执行window

  var  number = 1;

  var obj = {

    number:2,

    action:function( ){

      this.number = 5;

      (function( ){

        console.log(this.number)   // 1

      })( )

      console.log(this.number)  // 5

    }

  }

  obj.action( )

总结:this指向函数的调用者,没有调用者就指向window

猜你喜欢

转载自www.cnblogs.com/cuishuangshuang/p/12632595.html