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

if function does not exist write function - javascript - Stack Overflow

programmeradmin2浏览0评论

In php I'm writing the following

<?php
if(x != 0) {
echo "function myfunction(){};";    
}
?>

In javascript I wish to test if the function exists and if not write out an empty function

if(typeof myfunction != 'function'){
    function myfunction(){};
}

This works great in firefox but, in chrome even if the typeof equals function it still goes into and creates the empty function. I can't find a work around for chrome, i've tried if(!myfunction), if(typeof window.myfunction != 'function) but nothing seems to work here for chrome when everything seems to work in firefox. Any ideas?

In php I'm writing the following

<?php
if(x != 0) {
echo "function myfunction(){};";    
}
?>

In javascript I wish to test if the function exists and if not write out an empty function

if(typeof myfunction != 'function'){
    function myfunction(){};
}

This works great in firefox but, in chrome even if the typeof equals function it still goes into and creates the empty function. I can't find a work around for chrome, i've tried if(!myfunction), if(typeof window.myfunction != 'function) but nothing seems to work here for chrome when everything seems to work in firefox. Any ideas?

Share Improve this question asked Jan 12, 2012 at 17:05 Bret ThomasBret Thomas 3372 gold badges5 silver badges16 bronze badges 1
  • Still no answer? I have the same problem and the solution below doesn't work for me. – Luc CR Commented Dec 17, 2012 at 20:22
Add a comment  | 

2 Answers 2

Reset to default 40

Use a function expression, not a function declaration.

if(typeof myfunction != 'function'){
   window.myfunction = function(){};
}

(I'm using window since your last paragraph suggests you want a global function)

You should use strict comparison operator !==

if(typeof myFunction !== 'function'){
    window.myFunction = function(){}; // for a global function or
    NAMESPACE.myFunction = function(){}; // for a function in NAMESPACE 
}

Also try to keep js functions inside namespaces, this way you avoid collisions with other js libraries in the future.

发布评论

评论列表(0)

  1. 暂无评论