I am utilizing the decimal.js library for conducting financial calculations within Node. In my code, I have crafted a custom JSON.stringify replacer function. However, I have noticed a discrepancy in the results of property type tests conducted using instanceof
within the replacer function compared to outside of it.
Below is an executable example:
const myObj = {
myNum: new Decimal(0.3)
};
// output: 'Property "myNum" is a Decimal: true'
console.log('Property "myNum" is a Decimal:', myObj.myNum instanceof Decimal);
const replacer = (key, value) => {
if (key === 'myNum') {
// output: '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>
Can anyone explain this behavior?
Interestingly, when I substitute the Decimal
instance with an instance of a custom class, both instanceof
tests yield the same outcome, as anticipated:
function MyClass() {}
const myObj = {
myClass: new MyClass()
};
// output: 'Property "myClass" is a MyClass: true'
console.log('Property "myClass" is a MyClass:', myObj.myClass instanceof MyClass);
const replacer = (key, value) => {
if (key === 'myClass') {
// output: 'Property "myClass" is a MyClass: true'
console.log('Property "myClass" is a MyClass:', value instanceof MyClass);
}
return value;
}
JSON.stringify(myObj, replacer, 4);