js this指向

2018-09-25  本文已影响0人  神话降临

this指向调用该函数的对象

在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了

因为this的取值是执行上下文环境的一部分,每次调用函数,都会产生一个新的执行上下文环境。

this的取值,分四种情况

第一种情况

构造函数的this


     function Foo() {
        this.name = "test"
        this.age = 15
        console.log(this)  //Foo {name: "test", age: 15}
      }
      let foo = new Foo()
      console.log(foo.name)  // test
      console.log(foo.age)   // 15

看上面的代码
构造函数的this永远指向new出来的对象
注意构造函数的首字母要大写,如上代码的Foo
如果不进行new的操作而是直接调用Foo()那么这时就像一个普通函数,this指向window

第二种情况

对象的属性方法this指向

    let obj = {
        x: "test",
        say: function () {
            console.log(this.x)  // test
        }
    }
    obj.say()  

看上面的代码
如果函数作为对象的一个属性时,并且作为对象的一个属性被调用时,函数中的this指向该对象。
谁调用指向谁
注意,如果fn函数不作为obj的一个属性被调用,会是什么结果呢?

  let obj = {
       x: "test",
       fn: function () {
           console.log(this) //window
           console.log(this.x) //undefnd
        }
      }
var foo = obj.fn
 foo()

这个时候就相当于一个普通函数调用在这里foo()相当于window.foo()

第三种情况

函数用call或者apply调用
当一个函数被call和apply调用时,this的值就取传入的对象的值

   var one = {
       x: 1001
   }
   let other = {
       x: 10,
       fn: function () {
           console.log(this.x)   //1001
       }
   }
 other.fn.call(one)

第四种情况

普通调用,全局调用

  var x = 100
    function f() {
        console.log(this)  //window
        console.log(this.x) // 100
    }
f()

需要注意一种情况

  let obj = {
       x: 100,
       fn: function () {
           function f() {
               console.log(this)  //window
           }
           f()
       }
   }
   obj.fn()

这里的f()相当于普通函数调用

关于let const

讲this的时候为什么要讲let const
因为你申明的let const变量并没有挂载到window上

let x = 100;
    console.log(x)  //100
    console.log(this.x) //undefind

所以如果你想申明一个变量挂载到window上,就需要申明一个var变量
如果不需要就尽量用let const代替吧

好了,this的指向已经介绍完了
看完这篇文章相信你不用在死记硬背面试题了

上一篇 下一篇

猜你喜欢

热点阅读