JavaScript에 함수가 있는지 확인하는 방법?
I는 다음 이 가이드 플래시 통신에 새로운 JS를 만들.
내 코드는
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
?
(아래의 방법 중 하나만 시도해보십시오)
다음과 같이 해보십시오 :
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') { ... }
훨씬 깨끗하고 잘 작동합니다.
eval을 사용하여 문자열을 함수로 변환 하고이 evald 메소드가 존재하는지 확인하려는 경우 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
어때요?
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 문서를 참조하십시오 .
시도 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
이것이 제안 된 것을 보지 못했다 : me.onChange && me.onChange (str);
기본적으로 me.onChange가 정의되지 않은 경우 (시작되지 않은 경우) 후자를 실행하지 않습니다. me.onChange가 함수이면 me.onChange (str)가 실행됩니다.
더 나아가서 할 수도 있습니다.
me && me.onChange && me.onChange(str);
나도 비동기 인 경우.
속성이 실제로 함수인지 확인하기 위해 1 단계 더 나아가겠습니다.
function js_to_as( str ){
if (me && me.onChange && typeof me.onChange === 'function') {
me.onChange(str);
}
}
//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");
}
나를 위해 가장 쉬운 방법 :
function func_exists(fname)
{
return (typeof window[fname] === '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 메소드에서이를 정의합니다 (이 의견은 일부 브라우저 버그를 수용 할 수 있음)
typeof obj == 'function' || false
http://underscorejs.org/docs/underscore.html#section-143
function js_to_as( str ){
if (me && me.onChange)
me.onChange(str);
}
조건없이
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
가 올바르게 할당되지 않은 것 같습니다 .
get_ID 호출을 onclick 이벤트로 이동하면 처리해야합니다.
분명히 앞에서 언급 한대로 더 덫을 놓을 수 있습니다.
function js_to_as( str) {
var me = get_ID('jsExample');
if (me && me.onChange) {
me.onChange(str);
}
}
나는 항상 다음과 같이 확인합니다.
if(!myFunction){return false;}
이 함수를 사용하는 코드 앞에 배치하십시오.
함수 이름에 추가 된 변수 (이 경우 var 'x')에 따라 함수 이름이 다른 경우가있었습니다. 이것은 작동합니다 :
if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); }
이 간단한 jQuery 코드는 트릭을 수행해야합니다.
if (jQuery.isFunction(functionName)) {
functionName();
}
나는 대답을 시도했다; 하나:
console.log(typeof me.onChange);
'undefined'를 반환합니다. 사양에 'onChange'대신 'onchange'라는 이벤트 (카멜 케이스에 주목)가 있음을 알았습니다.
원래 수락 된 답변을 다음으로 변경하면 나에게 도움이되었습니다.
if (typeof me.onchange === "function") {
// safe to use the function
}
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';
}
느낌표 두 개를 넣으십시오. 확인하려는 기능 이름 앞에. 존재하면 true를 반환합니다.
function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false
jQuery 플러그인 인 함수를 확인하려면 $ .fn.myfunction을 사용해야합니다.
if (typeof $.fn.mask === 'function') {
$('.zip').mask('00000');
}
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
*/
또한이 문제에 대한 우아한 해결책을 찾고 있습니다. 많은 성찰 끝에이 방법이 가장 좋습니다.
const func = me.onChange || (str => {}); func(str)
;
여기에서 작업하고 확인하기위한 간단한 해결책이 함수의 존재 및 동적으로 기능을 트리거하는 다른 기능으로는;
트리거 기능
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');">
참고 URL : https://stackoverflow.com/questions/1042138/how-to-check-if-function-exists-in-javascript
'Programming' 카테고리의 다른 글
C # Windows 콘솔 앱에서 현재 줄을 어떻게 업데이트합니까? (0) | 2020.02.14 |
---|---|
문자열의 마지막 문자를 얻는 방법? (0) | 2020.02.14 |
MySQL에서 조인으로 삭제 (0) | 2020.02.14 |
투명한 ImageButton을 사용하는 방법 : Android (0) | 2020.02.14 |
유니 코드 문자열을 Python의 문자열로 변환 (추가 기호 포함) (0) | 2020.02.13 |