原型与this:toString为何返回非对象?代码中强制转换疑问
this相关问题 Let's walk through your questions with clear examples and explanations, since they tie into JavaScript's type conversion rules and prototype behavior.
问题1:toString方法未返回对象,是否由强制类型转换导致?
Short answer: No—this is actually the expected behavior of the toString method.
By design, toString is meant to return a string (a primitive value), not an object. The default Object.prototype.toString returns strings like "[object Object]" or "[object Foo]" for custom class instances. Even if you write a custom toString method, the language expects it to return a primitive (usually a string); if you intentionally make it return an object, JavaScript's type conversion system will kick in to resolve it to a primitive (by falling back to valueOf or throwing an error if that also doesn't return a primitive).
So the fact that toString doesn't return an object isn't caused by coercion—it's the method's intended purpose. Coercion only comes into play if you misuse toString by returning an object, forcing the engine to fix that mismatch.
问题2:代码输出差异与toString返回'Tjo'的原因
First, let's reprint your code for clarity:
const foo = function() { return this }; class Foo { toString() { return 'Tjo'}}; const obj = new Foo(); Foo.prototype.foo = foo; console.log('C = ' + obj.foo()); console.log(obj.foo());
Let's break down why you see "C = Tjo" and Foo {} instead of the Foo object twice:
First
console.logline:'C = ' + obj.foo()obj.foo()calls thefoofunction, which returnsthis. Sincefoois called as a method onobj,thisrefers toobj(the Foo instance).- The
+operator here is a string concatenation operator: when one operand is a string ('C = '), JavaScript automatically coerces the other operand to a string. - To convert
objto a string, JavaScript calls itstoStringmethod. You explicitly overrodetoStringin theFooclass to return'Tjo', so that's the value used in the concatenation. Hence, the output is"C = Tjo".
Second
console.logline:console.log(obj.foo())- Again,
obj.foo()returnsobj(the Foo instance). - However,
console.loghandles objects differently than string concatenation. Instead of callingtoString, it renders the object's structure (showing its class and any own properties—since yourobjhas no own properties, it showsFoo {}).
- Again,
As for why toString returns 'Tjo': you directly defined it in the Foo class! Class methods are added to the class's prototype, so your custom toString overrides the default Object.prototype.toString that would otherwise return something like "[object Foo]". This is intentional on your part—you wrote the method to return that string, so that's exactly what it does when called (whether explicitly or implicitly during coercion).
内容的提问来源于stack exchange,提问作者user10381988

