Object.prototype.valueOf()

Object 实例的 valueOf() 方法将 this 值转换为 到一个对象。此方法旨在由自定义 类型转换 逻辑的派生对象覆盖。

¥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.

Try it

语法

¥Syntax

js
valueOf()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

this 值,转换为对象。

¥The this value, converted to an object.

注意:为了使 valueOf 在类型转换期间有用,它必须返回一个原语。因为所有基本类型都有自己的 valueOf() 方法,所以调用 aPrimitiveValue.valueOf() 通常不会调用 Object.prototype.valueOf()

¥Note: In order for valueOf to be useful during type conversion, it must return a primitive. Because all primitive types have their own valueOf() methods, calling aPrimitiveValue.valueOf() generally does not invoke Object.prototype.valueOf().

描述

¥Description

JavaScript 将 valueOf 方法调用到 将对象转换为原始值。你很少需要自己调用 valueOf 方法;当遇到需要原始值的对象时,JavaScript 会自动调用它。

¥JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

该方法由 数值转换原始转换 优先调用,但 字符串转换 优先调用 toString(),而 toString() 很可能返回字符串值(即使对于 Object.prototype.toString() 基础实现也是如此),因此在这种情况下通常不会调用 valueOf()

¥This method is called in priority by numeric conversion and primitive conversion, but string conversion calls toString() in priority, and toString() is very likely to return a string value (even for the Object.prototype.toString() base implementation), so valueOf() is usually not called in this case.

所有从 Object.prototype 继承的对象(即除 null-原型对象 之外的所有对象)都继承 toString() 方法。Object.prototype.valueOf() 基本实现是故意无用的:通过返回一个对象,其返回值将永远不会被任何 原始转换算法。许多内置对象重写此方法以返回适当的原始值。当你创建自定义对象时,你可以重写 valueOf() 来调用自定义方法,这样你的自定义对象就可以转换为原始值。通常,valueOf() 用于返回对对象最有意义的值 - 与 toString() 不同,它不需要是字符串。或者,你可以添加 @@toPrimitive 方法,该方法允许对转换过程进行更多控制,并且对于任何类型转换始终优先于 valueOftoString

¥All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the toString() method. The Object.prototype.valueOf() base implementation is deliberately useless: by returning an object, its return value will never be used by any primitive conversion algorithm. Many built-in objects override this method to return an appropriate primitive value. When you create a custom object, you can override valueOf() to call a custom method, so that your custom object can be converted to a primitive value. Generally, valueOf() is used to return a value that is most meaningful for the object — unlike toString(), it does not need to be a string. Alternatively, you can add a @@toPrimitive method, which allows even more control over the conversion process, and will always be preferred over valueOf or toString for any type conversion.

示例

¥Examples

使用 valueOf()

¥Using valueOf()

基本 valueOf() 方法返回 this 值本身,如果尚未转换为对象,则将其转换为对象。因此,任何原始转换算法都不会使用它的返回值。

¥The base valueOf() method returns the this value itself, converted to an object if it isn't already. Therefore its return value will never be used by any primitive conversion algorithm.

js
const obj = { foo: 1 };
console.log(obj.valueOf() === obj); // true

console.log(Object.prototype.valueOf.call("primitive"));
// [String: 'primitive'] (a wrapper object)

重写自定义对象的 valueOf

¥Overriding valueOf for custom objects

你可以创建一个要调用的函数来代替默认的 valueOf 方法。你的函数不应采用任何参数,因为在类型转换期间调用时不会传递任何参数。

¥You can create a function to be called in place of the default valueOf method. Your function should take no arguments, since it won't be passed any when called during type conversion.

例如,你可以将 valueOf 方法添加到自定义类 Box 中。

¥For example, you can add a valueOf method to your custom class Box.

js
class Box {
  #value;
  constructor(value) {
    this.#value = value;
  }
  valueOf() {
    return this.#value;
  }
}

有了前面的代码,每当在要表示为原始值(但不是具体的字符串)的上下文中使用类型 Box 的对象时,JavaScript 都会自动调用前面代码中定义的函数。

¥With the preceding code in place, any time an object of type Box is used in a context where it is to be represented as a primitive value (but not specifically a string), JavaScript automatically calls the function defined in the preceding code.

js
const box = new Box(123);
console.log(box + 456); // 579
console.log(box == 123); // true

对象的 valueOf 方法通常由 JavaScript 调用,但你可以自己调用它,如下所示:

¥An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as follows:

js
box.valueOf();

在对象上使用一元加

¥Using unary plus on objects

一元加 在其操作数上执行 数字强制,这对于大多数没有 @@toPrimitive 的对象来说,意味着调用其 valueOf()。但是,如果对象没有自定义 valueOf() 方法,则基本实现将导致 valueOf() 被忽略,并使用 toString() 的返回值。

¥Unary plus performs number coercion on its operand, which, for most objects without @@toPrimitive, means calling its valueOf(). However, if the object doesn't have a custom valueOf() method, the base implementation will cause valueOf() to be ignored and the return value of toString() to be used instead.

js
+new Date(); // the current timestamp; same as new Date().getTime()
+{}; // NaN (toString() returns "[object Object]")
+[]; // 0 (toString() returns an empty string list)
+[1]; // 1 (toString() returns "1")
+[1, 2]; // NaN (toString() returns "1,2")
+new Set([1]); // NaN (toString() returns "[object Set]")
+{ valueOf: () => 42 }; // 42

规范

Specification
ECMAScript Language Specification
# sec-object.prototype.valueof

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看