Reputation: 4607
When using the webdev tools console, if type a browser object, it returns console
> console
Console { }
> console+""
"[object Console]"
> console.log(console)
undefined
> Console { }
Works in this way for all browser objects; But if I do it with my own object, the output don't have my objectName(MyObj), only "Object" like this:
> var MyObj=function(){}
undefined
> var instance = new MyObj();
undefined
> instance
Object { }
> instance+""
"[object Object]"
> console.log(instance);
undefined
Object { }
Is there a way to make my objects output behavior be the same of browser objects ? And, can anyone anyone explain me why ?
Upvotes: 0
Views: 2784
Reputation: 105955
You can override the toString()
method in MyObj.prototype
:
MyObj.prototype.toString = function(){ return "[object MyObj]";}
var MyObj = function(){};
MyObj.prototype.toString = function(){ return "[object MyObj]"; };
var instance = new MyObj();
console.log(instance + "");
// "[object MyObj]"
Upvotes: 4