我有以下代码。
function Test() {
this.myTest = "Test";
}
Test.prototype.toString = function testToString() {
return this.myTest;
};
var test = new Test();
console.log(test);
我希望这会打印Test
,但会打印Test { myTest: 'Test' }
。我认为重写toString
应该在尝试转换为字符串时使用该新函数。任何想法为什么这不起作用?
答案 0 :(得分:3)
根据规范(console.log - > Logger - > Printer)console.log
的实施最终取决于实施。
因此,在console.log(obj)
的实施环境中,您可能不仅仅是Printer("log", obj.toString())
。
答案 1 :(得分:0)
\documentclass{report}
\usepackage{tocloft,lipsum,pgffor,sectsty}
\setcounter{tocdepth}{3}% Include up to \subsubsection in ToC
% Font changes to ToC content of sectional units
\renewcommand{\cftpartfont}{\normalfont\sffamily\bfseries}% \part font in ToC
\renewcommand{\cftchapfont}{\normalfont\large\itshape} % \chapter font in ToC
\renewcommand{\cftsecfont}{\normalfont\slshape} % \section font in ToC
\renewcommand{\cftsubsecfont}{\normalfont\itshape} % \subsection font in ToC
\renewcommand{\cftsubsubsecfont}{\normalfont\small} % \subsubsection font in ToC
% Font changes to document content of sectional units
\renewcommand{\partfont}{\normalfont\Huge\bfseries}
\renewcommand{\chapterfont}{\normalfont\huge\bfseries}
\renewcommand{\sectionfont}{\normalfont\LARGE\bfseries}
\begin{document}
\tableofcontents% ToC
% Create a dummy document with multiple (5) levels of sectional units
\foreach \curpart in {First, Second, Third, Last} {
\part{\curpart{} part}
\foreach \curchap in {First, Second, Third, Last} {
\chapter{\curchap{} chapter} \lipsum[1]
\foreach \cursec in {First, Second, Third, Last} {
\section{\cursec{} section}\lipsum[2]
\foreach \cursubsec in {First, Second, Third, Last} {
\subsection{\cursubsec{} subsection}\lipsum[3]
\foreach \cursubsubsec in {First, Second, Third, Last} {
\subsubsection{\cursubsubsec{} subsubsection}\lipsum[4]
}% \subsubsection
}% \subsection
}% \section
}% \chapter
}% \part
\end{document}

答案 2 :(得分:0)
根据这里的一些答案,我能够通过使用以下代码解决这个问题。虽然它与现有的一些答案相似但略有不同,所以决定在这里发布。
function Test() {
this.myTest = "Test";
}
Test.prototype.toString = function testToString() {
return this.myTest;
};
var test = new Test();
console.log(test + "");
只需在+ ""
的末尾添加console.log
即可完美运行,并运行toString
功能。