Chat JS output is [object object] is how is it?

Chat JS output is [object object] is how is it?

Today in learning ES6 the Symboldata 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 type s=Symbol(abc)value is unique.

    var s2 = Symbol("abc"); // s2 = Symbol(abc)

    console.log(s1 === s2) // false, explain these two values ​​are not equal

  • If 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 objan object, it will call the toString()method converts it to a string, a toStringmethod may not know much about the junior partner MDN view the following explanation:


  • In addition nulland undefinedbeyond, the other type (numeric, boolean, string, object) has toString()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 each Objectinherited objects. If this method is not covered in the custom object, toString()returns " [object type]", which typeis a type of object.

objThe 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 objin 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.

Guess you like

Origin www.cnblogs.com/zhangguicheng/p/12081060.html