I was playing around with the toString method and when I tried to override a function's toString method, I could see the effect when I tried console.log-ging it. http://jsbin.com/bigocijuqo/1/edit?js,console.
function greet(){
console.log("Hello!");
}
console.log(greet);
greet.toString = function () {
return "Overridden toString";
};
console.log(greet);
produces
function greet(){
window.runnerWindow.proxyConsole.log("Hello!");
}
Overridden toString
However, when I tried the same with objects, it doesn't seem to be taking effect. http://jsbin.com/jebunakibi/1/edit?js,console
var ray = {
'name': 'Ray',
'fav_food': 'Carrots'
};
console.log(ray);
ray.toString = function () {
return "My name is " + this.name + " and I loooove " + this.fav_food;
};
console.log(ray);
produces
[object Object] {
fav_food: "Carrots",
name: "Ray"
}
[object Object] {
fav_food: "Carrots",
name: "Ray",
toString: function () {
return "My name is " + this.name + " and I loooove " + this.fav_food;
}
}
I expected the second console.log would print
My name is Ray and I loooove Carrots
I even tried changing the toString method in Object.prototype, but it's still not taking any effect. Can somebody explain what is wrong with this code?