iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
0
自我挑戰組

30 天 node.js 學習筆記系列 第 20

Day 20 CallBack

回調函數是JavaScript最常用的模式之一,但是一個常見的錯誤是,將包含this的方法直接當作回調函數。

    var counter = {
    	count :  0 ,
    	inc :  function () {
    			'use strict' 
    			this.count ++ ; 
    	}
    };
    function  callIt ( callback ) { 
    	callback ();
    }
    callIt ( counter.inc ) //-- 此時傳進去的方法是從counter擷取的function // TypeError: Cannot read property 'count' of undefined

上面代碼中,counter.inc方法被當作回調函數,傳入了callIt,調用時其內部的this指向callIt運行時所在的對象,即頂層對象window,所以得不到預想結果。注意,上面的counter.inc方法內部使用了嚴格模式,在該模式下,this指向頂層對象時會報錯,一般模式不會。

解決方法就是使用bind方法,將counter.inc綁定counter。

    var counter = {
    	count :  0 ,
    	inc :  function () {
    		'use strict' ;
    		 this.count ++ ; 
    	}
    };
    function  callIt ( callback ) { 
    	callback ();
    }
    callIt ( counter.inc.bind (counter));
    console.log ( counter . count ) // 1

還有一種情況比較隱蔽,就是某些數組方法可以接受一個函數當作參數。這些函數內部的this指向,很可能也會出錯。


上一篇
Day 19 Prototype
下一篇
Day 21 Curry
系列文
30 天 node.js 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言