JavaScript Object valueOf & toString All In One
class ArrayWrapper {
arr: number[];
constructor(nums: number[]) {
this.arr = nums;
}
// ✅ 改写 Object 内置方法 valueOf, 返回一个 number 整数
// ❓ object 相加 (本质上是 object 序列化后的 string 相加 ✅) => number 相加
valueOf(): number {
return this.arr.reduce((sum, i) => sum + i, 0);
}
// 序列化
toString(): string {
// return JSON.stringify(arr);
return `[${this.arr.join(',')}]`;
}
};
/*
valueOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
The valueOf() method of Object instances converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.
Object 实例的 valueOf() 方法将 this 值转换为对象。此方法旨在由派生对象重写以实现自定义类型转换逻辑。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
Instance methods
~https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/valueOf~ ❌
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf ✅
*/
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/