js中的對象方法中this指向問題


對象方法
調用this所在函數fn的是b,所以this指向b,b.a1='hello a3' ,b沒有a2屬性,b.a2=undefined
var a1='hello a1'
var a2='hello a2'
var b={
  a1:'hello a3',
  fn:function(){
    console.log(this.a1) // hello a3
    console.log(this.a2) // undefined
  }
}
b.fn()
換一種情況,var fn1=b.fn只是賦值,fn1()時才發生了調用,調用對象為window,this指向window
var a1='hello a1'
var a2='hello a2'
var b={
  a1:'hello a3',
  fn:function(){
    console.log(this.a1) // hello a1
    console.log(this.a2) // hello a2
  }
}
var fn1=b.fn
fn1()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM