예를 들어, 내가 가지고 있는 모든 변수를 다음과 같이 정의된다:
var a = function() {/* Statements */};
내가 원하는 건 어떤 유형의 가변입니다 같은 함수 함수은 있는지 확인합니다. 예:
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
How can I check in the way '변수' a '는' 기능을 유형의 경우 위에서 정의한?
밑줄, 영감을 받아 최종 이펑크션 함수는 다음과 같습니다.
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
[언더스코엘가이스] (http://underscorejs.org/) 은 더 정교한 하지만 매우 강력한 테스트:
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
참조: http://jsperf.com/alternative-isfunction-implementations
편집: 업데이트되도록 제안하세요 메리 페로프 http://schmidt. devlib. http://jsperf.com/alternative-isfunction-implementations/4 테스트를 하는 것이 더 빠를 수도 있다.
그래서 그들 모두 여러 가지 방법으로 내아기마저도 요약하십시오. < ol>; <, li>, 최선의 방법은 다음과 같습니다. < pre>;
함수은 푸 (v) {}}, {if (v instanceof 함수) / 뭔가 /
< /pre>; 가장 강력한 (no 문자열 비교) 에서 지원되는 브라우저, 우아한 솔루션 - 이 instanceof 작동자 그동안 아주 오랫동안 도왔으매 don& # 39 건, t - IE 6 작업하십시오 것입니다. < /li>;
< li>, 이후, 최선의 방법은 다음과 같습니다. < pre>;
함수은 푸 (v) {if (메리 페로프 v = " function";) / 뭔가 /}}, {
< /pre>; 단점은 code> typeof< /code> <;;; silent. 장애가 발생할 경우, 나쁜 것은, 그래서 오식 (예를 들어 finction" ";) - 이 경우, "만약 '은 그냥 가지고 있는지 모르는 복귀하십시오 거짓값 진실이며당신이 won& 오류 이후에 코드에서 # 39. < /li>;
< li>, 다음, 최선의 방법은 다음과 같습니다. < pre>;
함수은 이펑크션 (펑크션토치크) { var 게티페 = {}; 펑크션토치크 반품하십시오 & &; & # 39, & # 39 게티페스투스트링스콜 (펑크션토치크) = [객체에는 함수은];; }
< /pre>;
< pre>;
함수은 이펑크션 (x) { 오브ject.프로토티페스투스트링스콜 반품하십시오 & # 39, & # 39 (x) = [객체에는 함수은];; }
< /pre>;
< /li>; < /ol>;
$.isFunction(functionName);
angular.isFunction(value);
_.isFunction(value);
_.isFunction(object);
[참고] [5] node. js v4.0.0 이후 사용되지 않는
var util = require('util');
util.isFunction(object);
[3]: https://lodash.com/docs # 이펑크션 [4]: http://underscorejs.org/ # 이펑크션 [5]: https://nodejs.org/api/util.html # util_util_isfunction_object
'이' instanceof 시도하시겠습니까 작동자: 이 모든 기능을 '클래스' 기능을 상속됩니다 것으로 보인다.
// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();
// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false
뭔가 더 많은 기능을 지원 및 비동기 브라우저 포함될 수 있다.
const isFunction = value => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function);
테스트 후 마치:
isFunction(isFunction); //true
isFunction(function(){}); //true
isFunction(()=> {}); //true
isFunction(()=> {return 1}); //true
isFunction(async function asyncFunction(){}); //true
isFunction(Array); //true
isFunction(Date); //true
isFunction(Object); //true
isFunction(Number); //true
isFunction(String); //true
isFunction(Symbol); //true
isFunction({}); //false
isFunction([]); //false
isFunction("function"); //false
isFunction(true); //false
isFunction(1); //false
isFunction("Alireza Dezfoolian"); //false
Who& # 39 의 스타일을 찾는 사람들을 위해, 또는 더 많은 관심을 갖고 있는 메타 프로그래밍 기능을 활용할 수 있는 표현 방식을 살펴보는 것도 흥미로운 일이 될 수 있다 (타입 검사 등), it 등 람다 라이브러리란 하는 작업.
다음 코드를 미디어만을 map_layer 순결케 및 포린트프리 기능:
const R = require('ramda');
const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
const equalsSyncFunction = isPrototypeEquals(() => {});
const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
비동기 ',' ES2017 vmware. 이를 견제하려는 수 있도록 기능을 사용할 수 있습니다.
const equalsAsyncFunction = isPrototypeEquals(async () => {});
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
그 후 합칩니다 함께:
const isFunction = R.either(isSyncFunction, isAsyncFunction);
물론 함수는 null 값이 정의되지 않은 '대한' 보호할 수 있도록, 그래서 '와' safe" ";:
const safeIsFunction = R.unless(R.isNil, isFunction);
그리고 스니핏 완료하십시오 요약:
const R = require('ramda');
const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});
const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
const isFunction = R.either(isSyncFunction, isAsyncFunction);
const safeIsFunction = R.unless(R.isNil, isFunction);
// ---
console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));
그러나 이 솔루션을 사용할 수 있는 옵션이 기록하십시오) 에 비해 성능이 더 광범위한 사용은 표시할 수 있기 때문에 다른 고차 총괄하였습니다.
[_.IsFunction] [1] 로다시 사용할 경우 함께 할 수 있습니다.
_.isFunction(function(){});
// => true
_.isFunction(/abc/);
// => false
_.isFunction(true);
// => false
_.isFunction(null);
// => false
이 방법은 '진정한', '거짓' 되돌려줍니다 함수 값은 다른 경우.
[1]: https://lodash.com/docs/4.17.4 # 이펑크션
내가 찾은 기본 브라우저 기능을 사용하여 해당 테스트할 때 IE8 'toString', 'instanceof' 및 '메리 페로프' 작동하지 않습니다. 여기서 제대로 작동합니다 IE8 (내린 것으로 알고) 하는 방식이다.
function isFn(f){
return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);
또는 기본 기능을 통해 확인할 수 있습니다.
"getElementById" in document
하지만, 나는 항상, 아래 IE7 이 곳에 검토완료 작업하십시오 않습니다.
I think you can 의 프로토타입, 그냥 정의하시려면 플래깅 함수은 운영까지도 인스턴스입니다 테스트하려면 있는 상속됨 있는지 확인합니다.
Function.prototype.isFunction = true;
var foo = function(){};
foo.isFunction; // will return true
그러나 같은 플래깅 그리곤요 it& # 39 의 프로토타입 (prototype) 을 정의할 수 있으며 다른 것은 쓸모없는 것이 가장 쉬운 방법은 없지만, 만약 포함된 모듈에서는 완전히 제어할 수 있어야 합니다.
일부 이전 같은 솔루션을 사용하는 것이 메리 페로프 답변 보여주고 있다. 다음은 코드 조각이 노데지스,
function startx() {
console.log("startx function called.");
}
var fct= {};
fct["/startx"] = startx;
if (typeof fct[/startx] === 'function') { //check if function then execute it
fct[/startx]();
}