Bu örnekte, bir değişkenin işlev türünde olup olmadığını kontrol edecek bir JavaScript programı yazmayı öğreneceksiniz.
Bu örneği anlamak için, aşağıdaki JavaScript programlama konuları hakkında bilgi sahibi olmalısınız:
- JavaScript typeof Operatörü
- Javascript İşlev çağrısı ()
- Javascript Nesnesi toString ()
Örnek 1: instanceof Operatorünü kullanma
// 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);
Çıktı
Değişken işlev türünde değil Değişken işlev türündedir
Yukarıdaki programda, instanceof
operatör değişkenin türünü kontrol etmek için kullanılır.
Örnek 2: typeof Operator'ü kullanma
// 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);
Çıktı
Değişken işlev türünde değil Değişken işlev türündedir
Yukarıdaki programda, typeof
operatör ===
değişkenin türünü kontrol etmek için kesinlikle operatöre eşit olarak kullanılır .
typeof
Operatör değişken veri türünü verir. ===
değişkenin değer ve veri türü açısından eşit olup olmadığını kontrol eder.
Örnek 3: Object.prototype.toString.call () Yöntemini Kullanma
// 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);
Çıktı
Değişken işlev türünde değil Değişken işlev türündedir
Object.prototype.toString.call()
Yöntem nesne türünü belirten bir dize döndürür.