如果函数不存在写入函数 - javascript [英] if function does not exist write function - javascript

查看:136
本文介绍了如果函数不存在写入函数 - javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在php中,我写了以下内容:

 <?php 
if(x!= 0) {
echofunction myfunction(){};;
}
?>

在javascript中,我希望测试函数是否存在,如果不写出空函数

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



$ b $ p
$ b

这个在firefox中很好用,但在chrome中即使typeof equals函数也是如此仍然进入并创造空功能。我无法找到铬的工作,我试过如果(!myfunction),如果(typeof window.myfunction!='function),但似乎没有任何工作在Chrome浏览器,当一切似乎在Firefox中工作。任何想法?

解决方案

使用函数表达式,而不是函数声明。

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

(我正在使用 window 因为你的最后一段建议你想要一个全局函数)

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?

解决方案

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)

这篇关于如果函数不存在写入函数 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆