2

In javascript. How can I test if a variable is equal to function Number() or function String().

I reading a react prop from a schema definition for which the type is set as a property. Thus a have this.props.fieldType is a function Number() or function String().

I have tried:

 if(this.props.fieldType instanceof Number)

and

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

according to instanceof description but this does not work. Not sure why.

user2427829
  • 128
  • 1
  • 7
Gerrie van Wyk
  • 679
  • 8
  • 27

1 Answers1

5

trying to check if the property has a value of function Number() of function String()

If you literally mean the functions Number or String, use == (or ===):

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

If you mean "is it a number" or "is it a string", use typeof, not instanceof:

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

If you mean "is it a object created via new Number" (which would be really unusual) then instanceof is what you want:

if (this.props.fieldType instanceof Number) {

Examples of all three:

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);

You mentioned instanceof in relation to doing getPrototypeOf and an equality comparison. It's imporant to understand that those are very different things.

instanceof checks to see if the object (the left-hand operand) has the current prototype property of the function (the right-hand operand) anywhere in its prototype chain. It may not be the object's immediate prototype; it may be further down. For example:

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);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875