2016-11-08 6 views
0

JavaScriptで。変数がfunction Number()またはfunction String()に等しいかどうかをテストするにはどうすればよいですか。変数がfunction型の型かどうかをチェックする方法Number()またはfunction String()js

タイプがプロパティとして設定されているスキーマ定義からreact propを読み込んでいます。したがって、this.props.fieldTypefunction Number()またはfunction String()です。

私が試してみました:

if(this.props.fieldType instanceof Number) 

if(Object.getPrototypeOf(this.props.fieldType) === Number.prototype) 

instanceof descriptionによるが、これは動作しません。理由は分かりません。

+0

val ueは数字( '1'のような)か文字列(' 'foo" 'のような)ですか? –

+0

番号。プロパティが 'function String()'の 'function Number()'の値を持っているかどうかチェックしようとしています –

+1

'instanceof'チェックは' fieldType'が 'new Number()'または 'new String()'です。これは本当ですか? –

答えて

4

プロパティがfunction String()

function Number()の価値を持っている場合は、文字通り機能NumberまたはStringを意味する場合は、チェックを使用しようとする==(または===):

if (this.props.fieldType === Number) { 

「数字ですか」「それは文字列ですか?」という場合は、ではなくtypeofを使用してください:

:すべての3つの

if (this.props.fieldType instanceof Number) { 

例:

if (typeof this.props.fieldType === "number") { 

あなたが意味する場合は、(本当に珍しいだろう)、その後instanceofが何をしたいです「それは新しいNumber経由で作成されたオブジェクトがあります」

var props = { 
 
    numberFunction: Number, 
 
    number: 42, 
 
    numberObject: new Number(42) 
 
}; 
 
console.log(props.numberFunction === Number); 
 
console.log(typeof props.number === "number"); 
 
console.log(props.numberObject instanceof Number);


getPrototypeOfと同等性の比較に関しては、instanceofと記載しました。それらが非常に異なるものであることを理解することは重要です。オブジェクト(左オペランド)がどこそのプロトタイプチェーン内の関数(右オペランド)の現在prototype性質を有しているかどうかを確認するために

instanceofチェックします。オブジェクトの直接のプロトタイプではないかもしれません。さらに下に行くかもしれません。たとえば、次のようにこのよう

function Thing() { 
 
} 
 
var t = new Thing(); 
 
// The following is true, Object.prototype is in t's prototype chain 
 
console.log(t instanceof Object); 
 
// The following is false, t's prototype isn't Object.prototype; 
 
// Object.prototype is further down t's prototype chain 
 
console.log(Object.getPrototypeOf(t) === Object.prototype);

0

効率が問題にならないときに、アンダースコアの方法は、より効率的ですが、チェックするための最良の方法確かに、

function isFunctionA(object) { 
return object && getClass.call(object) == '[object Function]'; 
} 

、最終isFunction次のようになります。

function isFunction(functionToCheck) { 
var getType = {}; 
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; 
} 
関連する問題