javascript-如何获取对象以返回不是对象本身的值 [英] javascript - how to get an object to return a value that is not the object itself
问题描述
创建x = new Date()
对象时,如果将其放入console.log(x)
,则会输出字符串.
When creating a x = new Date()
object, if you put it into console.log(x)
a string will be output.
有没有一种方法可以使自定义对象返回一个本身不是对象的值
Is there a way to make a custom object that will return a different value that is not an object itself
推荐答案
基本上两个方法返回的值都不是对象本身.
Basically two methods returns values, which are not the object itself.
每个对象都有一个
toString()
方法,当该对象将被表示为文本值或以一种期望的方式引用一个对象时,该方法会自动被调用.默认情况下,toString()方法由Object
派生的每个对象继承.如果自定义对象中未覆盖此方法,则toString()返回"[object type]",其中 type 是对象类型.
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 fromObject
. If this method is not overridden in a custom object, `toString() returns "[object type]", where type is the object type.
JavaScript调用
valueOf
方法将对象转换为原始值.您很少需要自己调用valueOf
方法.当遇到需要原始值的对象时,JavaScript会自动调用它.
JavaScript calls the
valueOf
method to convert an object to a primitive value. You rarely need to invoke thevalueOf
method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
默认情况下,valueOf
方法由 Object
.每个内置核心对象都重写此方法以返回适当的值.如果对象没有原始值,则valueOf
返回对象本身.
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.
您可以在自己的代码中使用valueOf将内置对象转换为原始值.创建自定义对象时,可以覆盖Object.prototype.valueOf()
来调用自定义方法,而不是默认的Object
方法.
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.
要针对您的问题进行分解,可以将这两种方法都实现为自定义函数.
To break it down for your question, you can implement both methods to a custom function.
当两种方法都实现并返回原始值时,首先调用valueOf
.如果valueOf
返回一个对象,则会调用toString
方法.
When both methods are implemented and return primitive values, the valueOf
is called first. If valueOf
returns an object, toString
method is called.
您可能会看到以下文章:伪造的运算符重载于JavaScript
You might have a look to this article: Fake operator overloading in JavaScript
function Custom(value) {
this.value = value;
}
Custom.prototype.valueOf = function () {
console.log('valueOf');
return this.value * 5;
};
var custom = new Custom(7);
console.log('' + custom); // no toString
Custom.prototype.toString = function () {
console.log('toString');
return this.value * 3;
};
Custom.prototype.valueOf = function () {
console.log('valueOf');
return {};
};
console.log('' + custom);
这篇关于javascript-如何获取对象以返回不是对象本身的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!