this & arguments

  • this 是隱藏的第一個參數(shù),且一般是對象(如果不是對象,就顯得很沒有意義了)

      function f(){
          console.log(this)
          console.log(arguments)
      }
      f.call() // window
      f.call({name:'frank'}) // {name: 'frank'}, []
      f.call({name:'frank'},1) // {name: 'frank'}, [1]
      f.call({name:'frank'},1,2) // {name: 'frank'}, [1,2]
    

通過 .call 來調(diào)用函數(shù),call 的第一個參數(shù)是 this ,如果不傳,那默認(rèn)是 window,如果傳的參數(shù)不是對象,那么會自動轉(zhuǎn)換為對象類型,總之,this必須是對象?。?! [注意:是小寫的 window ,但 chrome瀏覽器 犯jian,顯示的卻是大寫的 Window]。

call 除了第一個參數(shù)外,后面的參數(shù) 都 屬于 arguments ,如果不傳參,那么 arguments 就是一個空數(shù)組 。arguments 是 一個 偽數(shù)組(只是形式和數(shù)組像,但不具備只有數(shù)組才有的一些方法)。

如果你不是用 call 來調(diào)用函數(shù),直接 f() 。例如 f(1),那么這個 1 就會被放在 arguments 里 ;這時候的 this 還是 window ,雖然你只傳了一個參數(shù) 1 。所以,要用 .call() ,不要 f(),因為f()對初學(xué)者不友好,。call()反而思路更清晰一些。

每個函數(shù)都有 return
如果你不寫 return,就相當(dāng)于寫了 return undefined

  • this 為什么必須是對象
    因為 this 就是函數(shù)與對象之間的羈絆

    var person = {
        name: 'frank',
        sayHi: function(person){
            console.log('Hi, I am' + person.name)
        },
        sayBye: function(person){
            console.log('Bye, I am' + person.name)
        },
        say: function(person, word){
            console.log(word + ', I am' + person.name)
        }
    }
    person.sayHi(person)
    person.sayBye(person)
    person.say(person, 'How are you')
    
    // 能不能變成 
    person.sayHi()
    person.sayBye()
    person.say('How are you')
    
    // 那么源代碼就要改了
    var person = {
        name: 'frank',
        sayHi: function(){
            console.log('Hi, I am' + this.name)
        },
        sayBye: function(){
            console.log('Bye, I am' + this.name)
        },
        say: function(word){
            console.log(word + ', I am' + this.name)
        }
    }
    // 如果你不想吃語法糖
    person.sayHi.call(person)
    person.sayBye.call(person)
    person.say.call(person, 'How are you')
    
    // 還是回到那句話:this 是 call 的第一個參數(shù)
    // this 是參數(shù),所以,只有在調(diào)用的時候才能確定
    person.sayHi.call({name:'haha'})  // 這時 sayHi 里面的 this 就不是 person 了
    // this 真的很不靠譜
    
    // 新手疑惑的兩種寫法
    var fn = person.sayHi
    person.sayHi() // this === person
    fn()  // this === window
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容