2014-11-20 33 views
0

我試圖讓我的頭圍繞如何使可選的回調jasvascript函數的參數如何使可選的回調paramters javascript函數

我不知道技術術語對我是什麼試圖實現的,所以它使尋找解決困難的,但是這可能是有用的其他新人

I'e,使用情況如下

MyFunction({ 
     start: function() { 
     }, 

     end: function() { 
     } 
    }); 
+1

能否請您更好地描述你的期望從這樣的功能?與具有其他可選參數的函數有什麼不同?什麼是「可選回調」的具體內容? – 2014-11-20 22:34:29

+1

有什麼問題?所有的JS參數都是可選的。 – sebnukem 2014-11-20 22:34:59

+0

回調是可選還是回調可以選擇接受參數? – 2014-11-20 22:39:31

回答

0

這裏有一個搗鼓你一個例子:http://jsfiddle.net/0csnrv7p/

代碼:

function myFunction(options) { 
    // You need something like this line if you want to handle the case 
    // where there are no arguments at all. If options is undefined then 
    // trying to access a property within it results in an error. 
    options = options || {}; 

    if (typeof options.start === 'function') { 
     options.start(); 
    } 

    // ... 
    // do stuff 
    // ... 

    if (typeof options.end === 'function') { 
     options.end(); 
    } 
} 


myFunction({ 
    start: function() { 
     console.log('start'); 
    }, 
    end: function() { 
     console.log('end'); 
    } 
}); 

這裏還有更多信息的鏈接:http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

0

你可以做到這兩個方面,我猜。要麼你有一個默認選項,類似:

function MyFunction(options) { 
    var defaults = { 
     start: function(){}, 
     end: function(){} 
    }; 

    // use jQuery.extend() or whatever you want 
    options = extend(default, options); 

    // Call a callback 
    options.start(); 
} 

這樣,它總是安全的調用回調,weither與否的爭論已定。

或者你可以檢查是否設置了回調,如果它是調用它。

function MyFunction(options) 

    // Call a callback 
    if('start' in options && typeof options.start === 'function') options.start(); 
}