最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Alternative to trycatch for checking if a function exists in javascript - Stack Overflow

programmeradmin0浏览0评论

The following statement is used because the method in question (refreshPartyList()) may not always be defined.

try {
  parent.document.getElementById("myId").contentWindow.refreshPartyList(param1, param2);
}catch(e){}

Currently using the above approach and it is working fine, but is there a better alternative?

The following statement is used because the method in question (refreshPartyList()) may not always be defined.

try {
  parent.document.getElementById("myId").contentWindow.refreshPartyList(param1, param2);
}catch(e){}

Currently using the above approach and it is working fine, but is there a better alternative?

Share Improve this question asked Nov 1, 2011 at 1:06 SnowrightSnowright 6254 gold badges15 silver badges22 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4
var e = parent.document.getElementById("myId").contentWindow;
if(e.refreshPartyList)
  e.refreshPartyList(param1, param2);

You can check if the method exists with a simple if:

   if (parent.document.getElementById("myId").contentWindow.refreshPartyList) {
       parent.document.getElementById("myId").contentWindow.refreshPartyList(param1, param2);
   }

Or better still, with jQuery (because the if does not guarantee it is a function):

   if (jQuery.type(parent.document.getElementById("myId").contentWindow.refreshPartyList) == 'function') {
var win = parent.document.getElementById("myId").contentWindow;
win.refreshPartyList && win.refreshPartyList(param1, param2);

Use x.method && x.method(...) to check whether the method exists.

发布评论

评论列表(0)

  1. 暂无评论