Chat JS output is [object object] is how is it?
Today in learning ES6 the Symbol
data type, when writing demo for the console output Symbol[object object]
after, it was a bit puzzled, access to relevant information to figure out why.
Before I explain, because some small partners may not come into contact with ES6, we first talk about some of the features of the ES6 used above:
const: declare a constant
Symbol: 7 data types in JS, represents a unique value. Symbol Symbol values are function generation type.
The
var s1 = Symbol("abc");
// Symbol generated value types=Symbol(abc)
value is unique.
var s2 = Symbol("abc");
//s2 = Symbol(abc)
console.log(s1 === s2)
// false, explain these two values are not equalIf the argument Symbol is an object, it will call the
toString()
method first converts it to a string.About Symbol A more detailed description of the teacher can refer to Ruan Yifeng entry ES6 standards .
Now that part of the output Symbol[object object]
code:
const obj = {
f() {
return "abc";
}
};
const sym = Symbol(obj);
console.log(sym); // Symbol[object object]
Because obj
an object, it will call the toString()
method converts it to a string, a toString
method may not know much about the junior partner MDN view the following explanation:
- In addition
null
andundefined
beyond, the other type (numeric, boolean, string, object) hastoString()
a method that returns the string representation of the respective values (does not modify the original variables).- Each object has a
toString()
method.- When the object is represented as a text value, or an object is automatically invoked when an expected reference string.
- By default,
toString()
methods are eachObject
inherited objects. If this method is not covered in the custom object,toString()
returns "[object type]
", whichtype
is a type of object.
obj
The object is our custom, but toString()
the method has not been covered, it will be returned [object object]
.
Now we try to overwrite toString()
method, as shown in the following code:
// ES5写法
var obj = {
toString: function() {
return "abc";
}
};
// ES6写法
const obj = {
toString() {
return "abc";
}
};
const sym = Symbol(obj);
console.log(sym); // Symbol(abc)
When we overwrite toString()
after method, custom objects obj
in the call toString()
when the method call is our custom toString()
method, the output is "abc"
. So the final result is Symbol(abc)
.
Finished, if impropriety please correct me oh.