3

I want a debugging output function to contain a test: if the object has a toString function, use it.

But then, every JavaScript object has a toString function, so what I really want is to check whether it has been assigned toString instead of just inheriting a default one.

What's the best way to do this? It occurs to me maybe you could exploit the fact that the inherited function isn't visible in for-in iteration, though it feels like there ought to be an O(1) solution.

rwallace
  • 31,405
  • 40
  • 123
  • 242

4 Answers4

3

something like obj.hasOwnProperty('toString')

CaldasGSM
  • 3,032
  • 16
  • 26
2

The result of obj.hasOwnProperty('toString') depends on the way how your toString implementation is created. I did some simple test:

function A() {
}

A.prototype.toString = function(){
   console.log("A.toString");
};

function B() {
   this.toString = function(){
      console.log("B.toString");
   }
}

var t = [new A(), new B(), new A()];

for(var i=0; i<t.length; i++) {
    var hasOwnToString = t[i].hasOwnProperty("toString");
    console.log(hasOwnToString);

    if(hasOwnToString) {
       t[i].toString();
    }
}

Result:

false
true
B.toString
false

For A style it's false, but for B style it's true

mjzr
  • 241
  • 1
  • 3
  • 8
1

You can check to see if the toString function is the same as Object (the object all objects descend from)

function hasUserPrototype(obj) {
    return Object.getPrototypeOf(obj).toString !== Object.prototype.toString;
}

See Check if an object has a user defined prototype?

function Foo() 
{
}

// toString override added to prototype of Foo class
Foo.prototype.toString = function()
{
    return "[object Foo]";
}

var f = new Foo();

function Boo() 
{
}

var g = new Boo();

function hasUserPrototype(obj) {
    return Object.getPrototypeOf(obj).toString !== Object.prototype.toString;
}

document.write(hasUserPrototype(f)); // true
document.write(hasUserPrototype(g)); // false
Community
  • 1
  • 1
Alexander Mistakidis
  • 3,130
  • 2
  • 20
  • 23
0
var x = {}
if (!(x.hasOwnProperty("toString"))) {
  x.toString = function() {
    return "I am X"
  }
}
x.toString()
// "I am X"
James Newton
  • 6,623
  • 8
  • 49
  • 113