this的幾種使用場景

  

首先,this要在執行時才能確認值,定義時沒法確認.而在es6的箭頭函數中,this則是在定義時所在的對象html

this對象有四種使用的場景:es6

第一種狀況: 全局下this  app

因爲全局下的變量是window的屬性,函數是window的方法函數

因此this

栗子:spa

function fn1 (){prototype

  return thishtm

}對象

console.log(fn1())  //windowblog

注意: 在嚴格模式下 「use strict」  this是undefined

第二種狀況:構造函數

(1).當函數做爲構造函數調用時,this表明new出來的對象;

(2).若是沒有使用new而是直接調用函數,this===window;

(3).不單單是構造函數的prototype,即使是在整個原型鏈中,this表明的也是當前對象的值;

栗子:

function Foo (name){

  this.name = name ;

  console.log(this)

}

var foo = new Foo('Emma');  //Foo {name: "Emma"} 

Foo() //window

第三種狀況:函數做爲對象的一個屬性

這裏有兩種狀況

(1).函數做爲對象的一個屬性被調用的時候,this指向的是該對象;

(2).函數做爲對象的一個屬性被賦值到另外一個變量中調用,this===window

栗子:

 

var obj = {

  x :10,

  fn:function(){

    console.log(this)

  }

}

obj.fn()   //當前對象

var newFn = obj.fn;  newFn() //window

第四種狀況: 函數用apply() call() bind()調用時,this取得是傳入的對象

他們的具體使用方法及不一樣點單獨總結了

https://www.cnblogs.com/emma-zhao/p/10687992.html

相關文章
相關標籤/搜索