[英]How to check if function exists in JavaScript?
我的代碼是
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'
然后=== 'function'
當然是多余的。
更簡單:
if (typeof obj === 'function') { ... }
更清潔,效果很好。
自ES2020以來,這在 JavaScript 中得到解決,自v3.7起在 Typescript 中使用Optional Chaining解決。
me.onChange?.(str)
如果onChange
存在,它會被調用。
如果onChange
不存在,則什么也不會發生:表達式返回undefined
。
因此,對於let value = me.onChange?.(str)
,如果onChange
不存在,則value
未定義。
注意,如果onChange
存在但不是一個函數,它會拋出一個TypeError
就像你將任何非函數調用為函數一樣。 可選的鏈接並沒有做任何魔法來消除這種情況。
怎么樣:
if('functionName' in Obj){
//code
}
例如
var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false
或至於你的情況:
if('onChange' in me){
//code
}
請參閱MDN 文檔。
如果您使用 eval 將字符串轉換為函數,並且想要檢查此 eval 方法是否存在,則需要在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
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
沒有看到這個建議:me.onChange && me.onChange(str);
基本上,如果 me.onChange 未定義(如果尚未啟動,它將是),那么它將不會執行后一部分。 如果 me.onChange 是一個函數,它將執行 me.onChange(str)。
你甚至可以更進一步,做:
me && me.onChange && me.onChange(str);
以防我也是異步的。
對我來說最簡單的方法:
function func_exists(fname)
{
return (typeof window[fname] === 'function');
}
//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");
}
放雙感嘆號即!! 在要檢查的函數名稱之前。 如果存在,它將返回 true。
function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false
function js_to_as( str ){
if (me && me.onChange)
me.onChange(str);
}
我將進一步確保該屬性確實是一個函數
function js_to_as( str ){
if (me && me.onChange && typeof me.onChange === 'function') {
me.onChange(str);
}
}
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';
}
我喜歡使用這種方法:
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
}
Underscore.js 庫在 isFunction 方法中將其定義為 this (評論建議可能會滿足某些瀏覽器錯誤)
typeof obj == 'function' || false
我遇到了函數名稱根據添加到函數名稱中的變量(在本例中為 var 'x' )而變化的情況。 這有效:
if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); }
如果您要檢查的函數是 jQuery 插件,則需要使用 $.fn.myfunction
if (typeof $.fn.mask === 'function') {
$('.zip').mask('00000');
}
這是用於檢查功能是否存在並由另一個功能動態觸發該功能的有效且簡單的解決方案;
觸發功能
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');">
簡而言之:捕獲異常。
我真的很驚訝沒有人在這篇文章中回答或評論 Exception Catch。
詳細信息:這是一個示例,我嘗試匹配一個以 mask_ 為前綴並以表單字段“name”為后綴的函數。 當 JavaScript 沒有找到該函數時,它應該拋出一個ReferenceError ,您可以在 catch 部分隨意處理它。
function inputMask(input) { try { let maskedInput = eval("mask_"+input.name); if(typeof maskedInput === "undefined") return input.value; else return eval("mask_"+input.name)(input); } catch(e) { if (e instanceof ReferenceError) { return input.value; } } }
沒有條件
me.onChange=function(){};
function getID( swfID ){
if(navigator.appName.indexOf("Microsoft") != -1){
me = window[swfID];
}else{
me = document[swfID];
}
}
function js_to_as( str ){
me.onChange(str);
}
我懷疑me
沒有正確分配 onload。
將 get_ID 調用移動到 onclick 事件中應該會處理它。
顯然,您可以如前所述進一步陷阱:
function js_to_as( str) {
var me = get_ID('jsExample');
if (me && me.onChange) {
me.onChange(str);
}
}
我總是這樣檢查:
if(!myFunction){return false;}
只需將其放在使用此功能的任何代碼之前
這個簡單的 jQuery 代碼應該可以解決問題:
if (jQuery.isFunction(functionName)) {
functionName();
}
我已經嘗試了接受的答案; 然而:
console.log(typeof me.onChange);
返回“未定義”。 我注意到規范聲明了一個名為“onchange”而不是“onChange”的事件(注意camelCase)。
將原始接受的答案更改為以下對我有用:
if (typeof me.onchange === "function") {
// safe to use the function
}
我也一直在尋找一個優雅的解決方案來解決這個問題。 經過多次思考,我發現這種方法最好。
const func = me.onChange || (str => {}); func(str)
const func = me.onChange || (str => {}); func(str)
;
我建議使用:
function hasMethod(subject, methodName) {
return subject != null && typeof subject[methodName] == "function";
}
第一個檢查subject != null
過濾掉沒有任何屬性的空值( null
和undefined
)。 如果沒有此檢查, subject[methodName]
可能會引發錯誤:
TypeError: (undefined|null) 沒有屬性
僅檢查真值是不夠的,因為0
和""
都是假的,但確實具有屬性。
在驗證該subject
不為空后,您可以安全地訪問該屬性並檢查它是否與typeof subject[methodName] == "function"
匹配。
將此應用到您的代碼中,您現在可以執行以下操作:
if (hasMethod(me, "onChange")) {
me.onChange(str);
}
function sum(nb1,nb2){
return nb1+nb2;
}
try{
if(sum() != undefined){/*test if the function is defined before call it*/
sum(3,5); /*once the function is exist you can call it */
}
}catch(e){
console.log("function not defined");/*the function is not defined or does not exists*/
}
然后是這個...
( document.exitPointerLock || Function )();
試試這個:
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;
}
為了說明前面的答案,這里有一個快速的 JSFiddle 片段:
function test () { console.log() } console.log(typeof test) // >> "function" // implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as : // var test = false if(test){ console.log(true)} else{console.log(false)} // test by the typeof method if( typeof test === "function"){ console.log(true)} else{console.log(false)} // confirm that the test is effective : // - entity with false value var test2 = false if(test2){ console.log(true)} else{console.log(false)} // confirm that the test is effective : // - typeof entity if( typeof test ==="foo"){ console.log(true)} else{console.log(false)} /* Expected : function true true false false */
// just pass your tested function name instead of myFunctionName
if ( $.isFunction($.fn.myFunctionName) ) {
console.log( 'write your code here.' );
}
這將驗證函數是否存在,如果存在則執行
me.onChange && me.onChange(str);
因此錯誤TypeError: me.onChange is not a function
被阻止。
我更喜歡使用lodash
庫,如下所示(看起來更干凈):
if (_.has(me, "onChange")) {
// your desired code here
}
// or generic one like
if (_.has(this, "some property or function name")) {
// your desired code here
}
function isFunction( o ) { return null !== o && "function" === typeof o && !!o.apply; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.