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
複製代碼
相關文章
相關標籤/搜索