JavaScript 的 this 指向

this 的定義

this 是一個指針,指向的是函數執行的環境對象

 

用幾個例子說明 this 的指向

  • 普通函數內的 this 指向執行環境對象,例子中的執行環境是 window
var a = 'window'
function fn(){
  let a = 'fn'
  return this.a
}
fn();        // 'window'
  • 構造函數創建的對象的函數內的 this 指向該對象,例子中的 this 指向是 obj
function Fn(){
  this.a = 'Fn'
  this.getA = function(){
    return this.a
  }
}
var obj = new Fn()    // {a:'Fn',getA(){return this.a}}
obj.a;        // 'Fn'
obj.getA()    // 'Fn'
  • 對象中的函數內的 this 指向對象本身,即對象爲該函數的執行環境。其本質是上例子的語法糖。
var a = 'window'
var obj = {
  a: 'obj',
  getA(){
    return this.a
  }
}
obj.getA();    // 'obj'
  • 賦值可能會使函數內的 this 指向發生改變
var a = 'window'
var obj1 = {
  a: 'obj1',
  getA: null
}
var obj2 = {
  a: 'obj2',
  getA(){
    return this.a
  }
}
console.log(obj2.getA())    // 'obj2'
obj1.getA = obj2.getA
console.log(obj1.getA())    // 'obj1'
var getA = obj2.getA
console.log(getA())         // 'window'
  • call() 和 apply() 方法可改變運行函數的作用域,兩個方法首個參數都是傳入"運行函數的作用域",例子中的 this 指向 obj1 和匿名對象。(文章最後簡單講述兩個函數的介紹)
obj1 = { a: 'obj1' }
obj2 = {
  a: 'obj2',
  getA(){
    return this.a
  }
}
var aValue = obj2.getA.apply(obj1);               // 'obj1'
// 也可以傳入匿名對象
var aValue = obj2.getA.apply({a:'anonymity'});    // 'anonymity'

 

apply() 和 call() 的差異及用法

  • apply() 接收兩個參數:運行的作用域(不指定可以填 null ) 和 傳遞給函數的參數所組成的數組(或"類數組") 。
var baseNum = 20
var obj = { baseNum: 10 }
function computer(addend, divisor) {
  let result = this.baseNum || 0
  return (result + addend) / divisor
}
var num = computer.apply(obj, [2, 5]);        // (10+2)/5=2.4
// 可以把函數的 arguments 傳遞給 "apply"
function computer2(addend, divisor) {
  return computer.apply(this, arguments)
}
var num2 = computer2(2, 5);                   // (20+2)/5=4.4
  • call() 與 apply() 類似,區別在於 "call" 接受的是若干個參數的列表,不多贅述。
var num = computer.call(obj, 2, 5);        // 所有參數展開傳遞

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章