gpt4 book ai didi

javascript - 如何用不是原始类型的正确类型覆盖 valueOf()?

转载 作者:行者123 更新时间:2023-11-30 11:08:30 28 4
gpt4 key购买 nike

假设我需要通过 Array 类型覆盖内部 valueOf()...

作为explained here valueOf() 方法返回指定对象的原始值...所以,我想我们可以将原始值设置为任何数据类型...可以吗?还是有限制?

这里是相同的链接示例,仅更改返回和测试:

function MyNumberType(n) {
this.number = n;
}
MyNumberType.prototype.valueOf = function() {
return [123,this.number];
};

const object1 = new MyNumberType(4);
console.log(object1 + [1,1]); // expected output: 123,41,1

最佳答案

Many operators and functions in JavaScript expect their arguments to have certain types. If they don’t, they are coerced (converted) to those types. Coercing an object to a primitive type is a two-step process: First, the object is converted to a primitive. Then, if necessary, the primitive is converted to the correct type. Two methods are used to convert an object to a primitive: valueOf() toString() 1

让我们看看将两个对象相乘时会发生什么:

function Foo() {
}

// valueOf returns an object which is not a primitive
Foo.prototype.valueOf = () => {
console.log('converting to primitive');
return {};
};

// valueOf returns an object which is not a primitive
Foo.prototype.toString = () => {
console.log('converting to string');
return 42;
};

const foo1 = new Foo();
const foo2 = new Foo();

console.log(foo1 * foo2);

如您所见,首先调用 valueOf() 将对象转换为其原始表示形式。然而,对象不是原始对象,因此接下来调用 toString()

您的代码的问题在于,正如@Thomas 所指出的,valueOf() 不返回原始值。因此调用 toString() 返回标准的 [object Object] 除非你覆盖它:

function MyNumberType(n) {
this.number = n;
}

MyNumberType.prototype.valueOf = function() {
// force `toString()` to be called
console.log('converting to primitive');
return {};
};

MyNumberType.prototype.toString = function() {
console.log('converting to string');
return `123,${this.number}`;
};

const object1 = new MyNumberType(4);
console.log(object1 + [1,1]); // expected output: 123,41,1

引用资料

  1. > http://2ality.com/2012/11/coercing-objects.html

关于javascript - 如何用不是原始类型的正确类型覆盖 valueOf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723423/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com