When creating a x = new Date()
object, if you put it into console.log(x)
a string will be output.
创建x = new Date()对象时,如果将其放入console.log(x),则会输出一个字符串。
Is there a way to make a custom object that will return a different value that is not an object itself
有没有办法使自定义对象返回不是对象本身的不同值
4 个解决方案
#1
0
Basically two methods returns values, which are not the object itself.
基本上两个方法返回值,而不是对象本身。
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.每个对象都有一个toString()方法,当要将对象表示为文本值或者以期望字符串的方式引用对象时,会自动调用该方法。默认情况下,toString()方法由来自Object的每个对象继承。如果在自定义对象中未覆盖此方法,则`toString()将返回“[object type]”,其中type是对象类型。
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.JavaScript调用valueOf方法将对象转换为原始值。您很少需要自己调用valueOf方法;当遇到期望原始值的对象时,JavaScript会自动调用它。
By default, the
valueOf
method is inherited by every object descended fromObject
. 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的每个对象继承。每个内置核心对象都会覆盖此方法以返回适当的值。如果对象没有原始值,则valueOf返回对象本身。
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 defaultObject
method.您可以在自己的代码中使用valueOf将内置对象转换为原始值。创建自定义对象时,可以重写Object.prototype.valueOf()以调用自定义方法而不是默认的Object方法。
To break it down for your question, you can implement both methods to a custom function.
要将其分解为您的问题,您可以将两种方法都实现为自定义函数。
When both methods are implemented and return primitive values, the valueOf
is called first. If valueOf
returns an object, toString
method is called.
当两个方法都实现并返回原始值时,首先调用valueOf。如果valueOf返回一个对象,则调用toString方法。
You might have a look to this article: Fake operator overloading in JavaScript
您可能会看一下这篇文章:在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);
#2
2
There is a function for that, toString, however if you just do console.log(new Test)
it will still output the object. But if your force it so print a string it will work: console.log('%s', new Test)
:
有一个函数,toString,但是如果你只是做console.log(新的测试),它仍然会输出对象。但是如果你强制它打印一个字符串就行了:console.log('%s',new Test):
function Test() {
}
Test.prototype.toString =
function () {
return "Something else";
}
console.log("%s", new Test);
> Something else
Or if you concatenate it with another string:
或者,如果您将其与另一个字符串连接:
var a = new Test;
console.log('Result: ' + a);
> Result: Something else
I use this a lot in my code to display a summary of the content of a object with data.
我在我的代码中经常使用它来显示带有数据的对象内容的摘要。
There is also valueOf:
还有valueOf:
Test.prototype.valueOf =
function () {
return 42;
}
console.log("%d", new Test);
> 3
#3
0
You can convert most of the objects to string as follows
您可以将大多数对象转换为字符串,如下所示
String(object)
like
x = String(new Date()); // now x is a string
Similarly
x = Boolean(0); // wil return an object
x = String(Boolean(0)); // will return a string
#4
0
Overwrite toString of an Object:
覆盖对象的toString:
My comment above refered to toString as well. You can use JSON.stringify to print out all properties of an object on the fly within an object's toString method:
我上面的评论也提到了toString。您可以使用JSON.stringify在对象的toString方法中即时打印对象的所有属性:
function MyObject() {
this.a = 'a';
this.b = 'b';
this.c = 'c';
}
MyObject.prototype.toString = function () {
return JSON.stringify(this);
};
console.log((new MyObject()).toString()); // {"a":"a","b":"b","c":"c"}
// or
console.log('new MyObject(): ' + new MyObject()); // new MyObject(): {"a":"a","b":"b","c":"c"}
Overwrite console.log:
Another try might be to overwrite console.log to print always strings (only tested in FF!):
另一个尝试可能是覆盖console.log以始终打印字符串(仅在FF中测试!):
// initialize this only once so that console.log prints out correctly
(function () {
var oldConsole = console.log;
console.log = function (obj) {
oldConsole(JSON.stringify(obj));
};
}) ();
// now console.log prints strings
console.log({
a: 'a'
}); // String: {"a":"a"}
console.log(new Date()); // String: "2017-01-19T19:09:49.673Z"
console.log(document); // String: {"location":{"href":"http://*.com/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121#41749121","origin":"http://*.com","protocol":"http:","host":"*.com","hostname":"*.com","port":"","pathname":"/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121","search":"","hash":"#41749121"},"jQuery112409140067213472354":3}
#1
0
Basically two methods returns values, which are not the object itself.
基本上两个方法返回值,而不是对象本身。
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.每个对象都有一个toString()方法,当要将对象表示为文本值或者以期望字符串的方式引用对象时,会自动调用该方法。默认情况下,toString()方法由来自Object的每个对象继承。如果在自定义对象中未覆盖此方法,则`toString()将返回“[object type]”,其中type是对象类型。
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.JavaScript调用valueOf方法将对象转换为原始值。您很少需要自己调用valueOf方法;当遇到期望原始值的对象时,JavaScript会自动调用它。
By default, the
valueOf
method is inherited by every object descended fromObject
. 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的每个对象继承。每个内置核心对象都会覆盖此方法以返回适当的值。如果对象没有原始值,则valueOf返回对象本身。
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 defaultObject
method.您可以在自己的代码中使用valueOf将内置对象转换为原始值。创建自定义对象时,可以重写Object.prototype.valueOf()以调用自定义方法而不是默认的Object方法。
To break it down for your question, you can implement both methods to a custom function.
要将其分解为您的问题,您可以将两种方法都实现为自定义函数。
When both methods are implemented and return primitive values, the valueOf
is called first. If valueOf
returns an object, toString
method is called.
当两个方法都实现并返回原始值时,首先调用valueOf。如果valueOf返回一个对象,则调用toString方法。
You might have a look to this article: Fake operator overloading in JavaScript
您可能会看一下这篇文章:在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);
#2
2
There is a function for that, toString, however if you just do console.log(new Test)
it will still output the object. But if your force it so print a string it will work: console.log('%s', new Test)
:
有一个函数,toString,但是如果你只是做console.log(新的测试),它仍然会输出对象。但是如果你强制它打印一个字符串就行了:console.log('%s',new Test):
function Test() {
}
Test.prototype.toString =
function () {
return "Something else";
}
console.log("%s", new Test);
> Something else
Or if you concatenate it with another string:
或者,如果您将其与另一个字符串连接:
var a = new Test;
console.log('Result: ' + a);
> Result: Something else
I use this a lot in my code to display a summary of the content of a object with data.
我在我的代码中经常使用它来显示带有数据的对象内容的摘要。
There is also valueOf:
还有valueOf:
Test.prototype.valueOf =
function () {
return 42;
}
console.log("%d", new Test);
> 3
#3
0
You can convert most of the objects to string as follows
您可以将大多数对象转换为字符串,如下所示
String(object)
like
x = String(new Date()); // now x is a string
Similarly
x = Boolean(0); // wil return an object
x = String(Boolean(0)); // will return a string
#4
0
Overwrite toString of an Object:
覆盖对象的toString:
My comment above refered to toString as well. You can use JSON.stringify to print out all properties of an object on the fly within an object's toString method:
我上面的评论也提到了toString。您可以使用JSON.stringify在对象的toString方法中即时打印对象的所有属性:
function MyObject() {
this.a = 'a';
this.b = 'b';
this.c = 'c';
}
MyObject.prototype.toString = function () {
return JSON.stringify(this);
};
console.log((new MyObject()).toString()); // {"a":"a","b":"b","c":"c"}
// or
console.log('new MyObject(): ' + new MyObject()); // new MyObject(): {"a":"a","b":"b","c":"c"}
Overwrite console.log:
Another try might be to overwrite console.log to print always strings (only tested in FF!):
另一个尝试可能是覆盖console.log以始终打印字符串(仅在FF中测试!):
// initialize this only once so that console.log prints out correctly
(function () {
var oldConsole = console.log;
console.log = function (obj) {
oldConsole(JSON.stringify(obj));
};
}) ();
// now console.log prints strings
console.log({
a: 'a'
}); // String: {"a":"a"}
console.log(new Date()); // String: "2017-01-19T19:09:49.673Z"
console.log(document); // String: {"location":{"href":"http://*.com/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121#41749121","origin":"http://*.com","protocol":"http:","host":"*.com","hostname":"*.com","port":"","pathname":"/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121","search":"","hash":"#41749121"},"jQuery112409140067213472354":3}