Skip to content

Instantly share code, notes, and snippets.

@alucky0707
Created February 28, 2013 12:02
Show Gist options
  • Save alucky0707/5056289 to your computer and use it in GitHub Desktop.
Save alucky0707/5056289 to your computer and use it in GitHub Desktop.
obj+""≠obj.toString()≠String(obj)っていう話 ref: http://qiita.com/items/8d80ca107555489710ea
// obj.toString()
str = obj+"";
"toString"
"valueOf"
"toString"
"obj1 valueOf"
"obj2 toString"
TypeError : ....
Object.prototype.valueOf = function(){
return this;
};
var
obj1 = {
toString : function(){
return {};
},
valueOf : function(){
rettrn "valueOf";
},
},
obj2 = {
toString : function(){
return {};
},
valueOf : function(){
return {};
},
};
console.log(String(obj1)); //=> "valueOf"
console.log(String(obj2)); //TypeError!
str = String(obj.toString());
var obj = {
toString : function(){
return "toString";
},
valueOf : function(){
return "valueOf";
},
};
console.log(obj.toString()); //=> "toString"
console.log(obj+""); //=> ???
console.log(String(obj)); // ???
var
obj1 = {
toString : function(){
return "obj1 toString";
},
valueOf : function(){
return "obj1 valueOf";
},
},
obj2 = {
toString : function(){
return "obj2 toString";
},
valueOf : function(){
return {};
},
},
obj3 = {
toString : function(){
return {};
},
valueOf : function(){
return {};
},
};
[obj1,obj2,obj3].forEach(function(obj){
console.log(obj+"");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment