我按照本指南创建了一个新的JS到Flash的通信。
我的代码是
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的错误是
me.onChange不是一个函数
我想优雅地降级,因为这不是我程序中最重要的功能。typeof
给出了同样的错误。
有什么建议吗?如何确保它的存在,然后只执行onChange
?
(下面的方法除了try catch一个以外都不能工作)
试试这样的方法。
if (typeof me.onChange !== "undefined") {
// safe to use the function
}
或者更好的方法是(按照UpTheCreek上调的评论)。
if (typeof me.onChange === "function") {
// safe to use the function
}
我有这个问题。
if (obj && typeof obj === 'function') { ... }
一直在抛出一个引用错误,如果 obj 碰巧是未定义的。
最后,我做了如下处理。
if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }
有同事向我指出,检查是否'的!=='undefined'
,然后=='函数'
当然是多余的。
更简单。
if (typeof obj === 'function') { ... }
更加干净,效果很好。
如果你正在使用eval将字符串转换为函数,并且你想检查这个eval'd方法是否存在,你'会想在一个eval里面使用typeof和你的函数字符串。
var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"
不要反过来在eval上尝试typeof。 如果你这么做了,就会抛出一个ReferenceError。
var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined
试试typeof
--找'undefined'
表示不存在,'function'
表示是函数。
[JSFiddle for this code][1] 。
function thisishere() {
return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);
或者作为一个如果。
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
[1]:
//Simple function that will tell if the function is defined or not
function is_function(func) {
return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}
//usage
if (is_function("myFunction") {
alert("myFunction defined");
} else {
alert("myFunction not defined");
}
Underscore.js库在isFunction方法中这样定义(评论认为这可能会照顾到一些浏览器的错误)。
typeof obj == 'function' || false
我喜欢用这种方法。
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
用法。
if ( isFunction(me.onChange) ) {
me.onChange(str); // call the function with params
}
function function_exists(function_name)
{
return eval('typeof ' + function_name) === 'function';
}
alert(function_exists('test'));
alert(function_exists('function_exists'));
或
function function_exists(func_name) {
// discuss at: http://phpjs.org/functions/function_exists/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Steve Clay
// improved by: Legaev Andrey
// improved by: Brett Zamir (http://brett-zamir.me)
// example 1: function_exists('isFinite');
// returns 1: true
if (typeof func_name === 'string') {
func_name = this.window[func_name];
}
return typeof func_name === 'function';
}