Object.getConstructorOf();

Brendan Eich brendan at mozilla.org
Sat Sep 20 12:12:44 PDT 2014


L2L 2L wrote:
> I see the value of this, cause it denote not only the constructor, but what an object is:
>
> Object.getConstructorOf("")//String
> Object.getConstructorOf(0)//Number
> Object.getConstructorOf(function(){})//Function
> Object.getConstructorOf({})//Object
> Object.getConstructorOf([]);//Array
>
> If you try the first to with Object.getPrototypeOf("");
> Object.getPrototypeOf(0);
>
> You'll get an error message, cause primitive value don't have prototype. But they do have wrapper objects; constructor objects.
>
> This to me is a needed feature of the language.

It's not a "kernel language" feature, as you showed -- it is library 
code that can be built on top of the core language. And you are right 
that we seem to observe a fair amount of

Object.prototype.toString.call(x).slice(8, -1)

for value x.

However, getConstructorOf("") returning "String" (a string value), 
instead of the constructor function, is misleading. But returning the 
constructor function reference is wrong for primitive values, because 42 
!== new (42).constructor(42). Primitives have value not reference semantics.

What you are really proposing is an Object.getToStringTag method. But in 
ES6, that is just x[Symbol.toStringTag], if I'm not mistaken. So do we 
really need Object.getToStringTag(x), which is longer?

See 
http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring 
for the ES6 spec.

Then you could argue that an Object "static method" is better both to 
hide the Symbol.toStringTag detail and to enable polyfilling on pre-ES6 
browsers. That's a fair point.

/be


More information about the es-discuss mailing list