I'm using decimal.js for some financial calculations in Node. I'm writing a custom JSON.stringify replacer function, but when I test the property types using instanceof
, I get a different result than when I do the same test outside of the replacer function.
Here's a runnable example:
const myObj = {
myNum: new Decimal(0.3)
};
// logs 'Property "myNum" is a Decimal: true'
console.log('Property "myNum" is a Decimal:', myObj.myNum instanceof Decimal);
const replacer = (key, value) => {
if (key === 'myNum') {
// logs 'Property "myNum" is a Decimal: false'
console.log('Property "myNum" is a Decimal:', value instanceof Decimal);
}
if (value instanceof Decimal) {
return value.toNumber()
} else {
return value;
}
}
JSON.stringify(myObj, replacer, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.0.0/decimal.js"></script>
Why is this happening?
If I replace the Decimal
instance with an instance of my own custom class, both instanceof
tests behave the same, as expected:
function MyClass() {}
const myObj = {
myClass: new MyClass()
};
// logs 'Property "myClass" is a MyClass: true'
console.log('Property "myClass" is a MyClass:', myObj.myClass instanceof MyClass);
const replacer = (key, value) => {
if (key === 'myClass') {
// logs 'Property "myClass" is a MyClass: true'
console.log('Property "myClass" is a MyClass:', value instanceof MyClass);
}
return value;
}
JSON.stringify(myObj, replacer, 4);