gpt4 book ai didi

javascript - 当没有指定键时,是否可以在对象上设置默认的 getter?

转载 作者:行者123 更新时间:2023-11-30 21:18:57 24 4
gpt4 key购买 nike

让 obj = {value:'foo'};

给定对象 obj,我很好奇是否可以对其进行调整以便 console.log(obj) 输出 "foo" ,而不是默认定义/类型。

let obj = {
value: 'foo',
get() {
return this.value;
}
};

console.log( obj ); // want: "foo"; get: "[object Object]" (or the like)
console.log( obj.get() ); // "foo"

注意:我意识到答案很可能是“否”,原因有很多(比如这是个坏主意),但这肯定会使这项任务更容易(将 bool 值转换为对象)。

最佳答案

基本上有两种方法返回值,这些值不是对象本身。

Object#toString

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, `toString() returns "[object type]", where type is the object type.

Object#valueOf

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.

By default, the valueOf method is inherited by every object descended from Object. Every built-in core object overrides this method to return an appropriate value. If an object has no primitive value, valueOf returns the object itself.

You can use valueOf within your own code to convert a built-in object into a primitive value. When you create a custom object, you can override Object.prototype.valueOf() to call a custom method instead of the default Object method.

为了解决您的问题,您可以将这两种方法都实现为自定义函数。

当这两个方法都实现并返回原始值时,首先调用 valueOf。如果 valueOf 返回一个对象,则调用 toString 方法。

你可以看看这篇文章:Fake operator overloading in JavaScript

let obj = {
value: 'foo',
get() { return this.value; },
toString: _ => 'fourty',
valueOf: _ => 40
};

console.log(obj + 2);
console.log(obj + 'two');
console.log(obj.toString() + 'two');
console.log(obj);
console.log(obj.get() ); // "foo"
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 当没有指定键时,是否可以在对象上设置默认的 getter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45381260/

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