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