我的代码是
function getID( swfID ){
if(navigator.appName.indexOf("Microsoft") != -1){
me = window[swfID];
}else{
me = document[swfID];
}
}
function js_to_as( str ){
me.onChange(str);
}
然而,有时我的onChange不加载。Firebug错误
我。onChange不是一个函数
我想优雅地降级,因为这不是我的程序中最重要的特性。Typeof给出相同的错误。
关于如何确保它存在,然后只执行onChange有什么建议吗?
(下面的方法除了try catch one work之外都没有)
如果你正在使用eval将一个字符串转换为函数,并且你想检查这个eval方法是否存在,你会想在eval中使用typeof和你的函数字符串:
var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"
不要反过来尝试一种类型的eval。如果你这样做,ReferenceError将被抛出:
var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined
试试typeof——用'undefined'表示它不存在,用'function'表示函数。这段代码的JSFiddle
function thisishere() {
return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);
或作为if:
if (typeof thisishere === 'function') {
// function exists
}
或者在一行中返回一个值:
var exists = (typeof thisishere === 'function') ? "Value if true" : "Value if false";
var exists = (typeof thisishere === 'function') // Returns true or false
这里有一个工作和简单的解决方案,检查一个函数的存在性,并由另一个函数动态触发该函数;
触发函数
function runDynamicFunction(functionname){
if (typeof window[functionname] == "function") { //check availability
window[functionname]("this is from the function it"); // run function and pass a parameter to it
}
}
现在可以用PHP动态生成函数
function runThis_func(my_Parameter){
alert(my_Parameter +" triggerd");
}
现在可以使用动态生成的事件调用该函数
<?php
$name_frm_somware ="runThis_func";
echo "<input type='button' value='Button' onclick='runDynamicFunction(\"".$name_frm_somware."\");'>";
?>
你需要的HTML代码是
<input type="button" value="Button" onclick="runDynamicFunction('runThis_func');">
试试这个:
Window.function_exists=function(function_name,scope){
//Setting default scope of none is provided
If(typeof scope === 'undefined') scope=window;
//Checking if function name is defined
If (typeof function_name === 'undefined') throw new
Error('You have to provide an valid function name!');
//The type container
var fn= (typeof scope[function_name]);
//Function type
If(fn === 'function') return true;
//Function object type
if(fn.indexOf('function')!== false) return true;
return false;
}
请注意,这是我用手机写的
可能包含一些大写问题和/或其他需要的更正,例如函数名
如果你想让PHP这样的函数检查是否设置了var:
Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}
我建议使用:
function hasMethod(subject, methodName) {
return subject != null && typeof subject[methodName] == "function";
}
第一个检查主题!= null过滤掉没有任何属性的null值(null和undefined)。如果没有这个检查,主题[methodName]可能会抛出一个错误:
TypeError:(undefined|null)没有属性
只检查一个真值是不够的,因为0和""都是假的,但确实有属性。
在确认subject不是null之后,你可以安全地访问属性并检查它是否匹配typeof subject[methodName] == "function"。
将此应用到您的代码,您现在可以做到:
if (hasMethod(me, "onChange")) {
me.onChange(str);
}