JavaScript Object valueOf & toString All In One
JavaScript Object valueOf & toString All In One
Object.prototype.valueOf()
& Object.prototype.toString()
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 ✅
demos
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(',')}]`;
}
};
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18194293
未经授权禁止转载,违者必究!