Ebben a példában megtanul olyan JavaScript programot írni, amely ellenőrzi, hogy egy változó függvény típusú-e.
A példa megértéséhez ismernie kell a következő JavaScript programozási témákat:
- Operator JavaScript típusa
- Javascript funkcióhívás ()
- Javascript Object toString ()
1. példa: Az Operator példányának használata
// program to check if a variable is of function type function testVariable(variable) ( if(variable instanceof Function) ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);
Kimenet
A változó nem függvénytípusú A változó függvénytípusú
A fenti programban az instanceof
operátort használják a változó típusának ellenőrzésére.
2. példa: A Typeof Operator használata
// program to check if a variable is of function type function testVariable(variable) ( if(typeof variable === 'function') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);
Kimenet
A változó nem függvénytípusú A változó függvénytípusú
A fenti programban az typeof
operátort szigorúan az operátorral használják ===
a változó típusának ellenőrzésére.
Az typeof
operátor megadja a változó adattípust. ===
ellenőrzi, hogy a változó értéke és adattípusa tekintetében megegyezik-e.
3. példa: Az Object.prototype.toString.call () módszer használata
// program to check if a variable is of function type function testVariable(variable) ( if(Object.prototype.toString.call(variable) == '(object Function)') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);
Kimenet
A változó nem függvénytípusú A változó függvénytípusú
A Object.prototype.toString.call()
metódus olyan karakterláncot ad vissza, amely meghatározza az objektumtípust.