I would like to know what's behind the scenes when I print an object in the console (like in the situation illustrated in the image). How can I define a special function inside the object for printing my own code instead of all the attribute of the object (the equivalent of toString in Objective-C)? For example if I evaluate a
in the console I want to print only the string "hello" and not all {one: 1, two: 2, hello: "hello"}
. Can I do it without using console.log() or similar functions?
Well, I am not sure if this is your question, but you could always override the toString() method of the object.
var a = {a:"something", hello:"hello", toString:function(){console.log(this.hello)}};
a.toString() // prints hello
Hope that helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.