Search code examples
javascriptnode.jsv8

Use Object.create and toString.call() to return '[object Rectangle]'


In node: if I do

var Shape = {
  x:0,
  y:0
}

var rectangle = Object.create(Shape);

I can get:

toString.call(rectangle);
//'[object Object]'
toString.call(Shape);
//'[object Object]'
toString.call({});
//'[object Object]'

Is there a way to effect something like:

toString.call(rectangle);
'[object Shape]'

I'm aware that I could override Shape.toString() or create a new Shape.toClassString() method but I'm interested in the toString.call() implementation. Is this a v8-necessary issue?


Solution

  • You can have a look at the specification: http://es5.github.com/#x15.2.4.2.

    Basically, the default implementation takes the internal [[Class]] property and concatenates it to the resulting string. Since both Shape and rectangle are plain objects, their internal [[Class]] property is Object. You have to override toString or create the object with a constructor function.

    I don't think V8 or Node.js give you any additional possibilities to override this, but I don't know for sure.