[Javascript] call 多年的誤區總算今天踩了 call 呼叫 this 直接 TypeError: Cannot read property

但是好巧不巧今天使用以下方法直接給你爆錯
// index.js
var obj={
    actionName:"qq",
    testCall :function(b){
        console.log(this.actionName+" "+b); //
    }
}
obj.testCall.call(null,22);

錯誤訊息: TypeError: Cannot read property 'actionName' of undefined

解決辦法:

// index.js
var obj={
    actionName:"qq",
    testCall :function(b){
        console.log(this.actionName+" "+b); //
    }
}
obj.testCall.call(obj,22);

就是要把call 的參數中的第一參數帶入, 因為第一個參數是 this

原理

因為在一般OO中視絕對不能這樣寫的
this=SomeVale;

但是Javascript 是允許你換掉...

this / super ...  

留言

  1. Do you realize there is a 12 word sentence you can communicate to your man... that will trigger deep emotions of love and instinctual attractiveness for you buried within his chest?

    That's because deep inside these 12 words is a "secret signal" that fuels a man's impulse to love, idolize and look after you with his entire heart...

    12 Words That Trigger A Man's Desire Response

    This impulse is so built-in to a man's genetics that it will make him try better than before to make your relationship as strong as it can be.

    In fact, fueling this dominant impulse is so essential to having the best possible relationship with your man that the second you send your man one of the "Secret Signals"...

    ...You'll instantly notice him expose his heart and soul to you in a way he's never expressed before and he'll perceive you as the one and only woman in the universe who has ever truly understood him.

    回覆刪除

張貼留言

這個網誌中的熱門文章

angular 如何Http 如何設定 CORS (Cross-Origin Resource Sharing)

Google Map 單車路徑計算坡度和角度小工具

Google URL Shortener API 快速教學