valueof toString

本文深入探讨了JavaScript中高阶函数add的实现方式,并通过不同的示例展示了如何使用该函数来执行加法操作。此外,还研究了valueOf和toString方法在不同对象上下文中的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

valueof toString


add(1)(2) // 3

add(1, 2, 3)(10) // 16

add(1)(2)(3)(4)(5) // 15



function add() {

    var args = Array.prototype.slice.call(arguments);


    return function() {

        var arg2 = Array.prototype.slice.call(arguments);

        return args.concat(arg2).reduce(function(a, b){

            return a + b;

        });

    }

}


add(1)(2) // 3

add(1, 2)(3) // 6

add(1)(2)(3) // Uncaught TypeError: add(...)(...) is not a function(…)



function add () {

var args = Array.prototype.slice.call(arguments);


var fn = function () {

var arg_fn = Array.prototype.slice.call(arguments);

return add.apply(null, args.concat(arg_fn));

}


fn.valueOf = function () {

return args.reduce(function(a, b) {

return a + b;

})

}


return fn;

}


var a = {a : 1}

undefined

a + 1

"[object Object]1"



a = {

 toString () {

   return '1111'

 }

}

Object {}

a + 1

"11111"



var aa = {

 toString : function () {

return {}

 },

 valueOf : function () {

  return '+1'

 }

}

undefined

aa + 1

"+11"



function xdh () {

 

}


xdh.valueOf = () => {

  console.log("valueof")

 return {}

}


xdh.toString = () => {

  console.log("toString")

  return 'sadasda'

}

() => {

  console.log("toString")

  return 'sadasda'

}

xdh

VM3052:6 valueof

VM3052:11 toString

sadasda



object 一般情况下 先调用 valueOf 后调用toString

转载于:https://www.cnblogs.com/kitebear/p/6500847.html

### JavaScript `valueOf` 和 `toString` 方法的区别及用法 #### 定义与作用 在 JavaScript 中,对象到原始值的转换通过两个特殊的方法实现:`toString()` 和 `valueOf()`. 这些方法允许开发者定义当对象被当作原始值处理时的行为[^1]. - **`toString()`**: 此方法返回表示该对象的一个字符串。通常用于提供关于对象类型的描述性信息。 - **`valueOf()`**: 返回对象对应的原始值。如果对象本身代表某种数值,则此方法应返回相应的数值形式;对于其他情况,默认行为取决于具体对象类型. #### 使用场景对比 ##### `toString` 主要用于获取对象的字符串表示形式: ```javascript let obj = { name: "Alice", age: 25 }; console.log(obj.toString()); // "[object Object]" ``` 可以自定义类中的 `toString` 方法来改变默认输出: ```javascript class Person { constructor(name, age) { this.name = name; this.age = age; } toString() { return `${this.name}, ${this.age}`; } } const person = new Person('Bob', 30); console.log(person.toString()); // Bob, 30 ``` ##### `valueOf` 用来获得对象所代表的实际数据值,在某些运算上下文中自动调用(比如算术操作符)。对于内置对象来说,它会尝试返回最接近于原生类型的值: ```javascript // 对象实例化 var numObj = new Number(42); // 调用 valueOf 获取内部存储的真实数字 console.log(numObj.valueOf()); // 42 ``` 同样也可以重写 `valueOf` 来适应特定需求: ```javascript class Point { constructor(x, y) { this.x = x; this.y = y; } valueOf() { return Math.sqrt(this.x * this.x + this.y * this.y); } } const point = new Point(3, 4); console.log(point.valueOf()); // 5 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值