Javascript函数中的this

和变量不一样关键字this没有做用域限制,this指代运行环境的上下文,它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用(全局变量中表明window对象)。bash

函数在不一样的使用场合,其内部的this也会指代不一样的对象。app

做为普通函数调用

当函数做为普通函数调用的时候this指代window, 在严格模式下指代undefined;函数

严格模式下post

"use strict";
function fn() {
  console.log(this)
}
fn()     // undefined
复制代码

非严格模式下this

function fn() {
  console.log(this)
}
fn()     // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
复制代码
做为对象的方法调用

当函数做为对象的方法调用时, this指代调用该方法的对象;spa

var obj = {
  name: "hah",
  getName: function() {
    console.log(this === obj)
  }
}
obj.getName()      //  true

//嵌套函数不会从调用它的函数中继承this

var obj = {
  name: "hah",
  getName: function() {
    console.log(1, this === obj)
    console.log(2, this === window)
    fn()
    function fn() {
      console.log(3, this === obj)
      console.log(4, this === window)
    }
  }
}
obj.getName()     //  1, true  2, false  3, false   4, true
复制代码
做为构造函数调用

当函数做为构造函数调用时, this指向它新建立的对象。code

function Animal(name) {
  this.name = name
  console.log(this)
}
var cat = new Animal("cat");   // Animal {name: "cat"}
复制代码
bind、call、apply调用时

当函数经过bind、call、apply调用时,会改变内部函数体 this的指向, this指代bind、call、apply传入的第一个参数;对象

var emptyObj = {}
var obj = {
  name: "hah",
  getName: function() {
    console.log(this === obj)
    console.log(this === emptyObj)
  }
}
obj.getName.call(emptyObj)       // false true
obj.getName.apply(emptyObj)     // false true
obj.getName.bind(emptyObj)()    // false true
复制代码
相关文章
相关标签/搜索