@@toStringTag spoofing for null and undefined

Allen Wirfs-Brock allen at wirfs-brock.com
Thu Jan 22 08:23:36 PST 2015


On Jan 21, 2015, at 6:09 PM, Mark S. Miller wrote:

> 
> 
> On Wed, Jan 21, 2015 at 6:01 PM, Allen Wirfs-Brock <allen at wirfs-brock.com> wrote:
> 
> On Jan 21, 2015, at 2:09 PM, Mark S. Miller wrote:
> 
>> // old ES5 code
>> 
>> function f(allegedDate) {
>>   if (({}).toString.call(allegedDate) === "[object Date]") {
>>     JSON.stringify(allegedDate); // "[]" impossible in ES5

actually it isn't impossible.  allegedDate could have a `toJSON` method that returns `"[]`

This is a pretty good example of why this sort of brand check is so problematic.  It is based upon and supports the misperception that such a branded object will have all of the specified initial characteristics of the correspond built-in.




>>     Array.isArray(allegedDate); // true impossible in ES5
>>     Date.prototype.getYear.call(allegedDate); // error impossible in ES5
>>   }
>> }
>> 
>> 
>> // new ES6 code
>> 
>> const fakeDate = [];
>> const defProp = Object.defineProperty;
>> defProp(fakeDate, Symbol.toStringTag, { value: "[object Date]" });
>> f(fakeDate); // all ES5 impossible behaviors happen
> 
> not quite.  The last of your tests (getYear) will still fail because fakeDate is not internally branded as a date. 
> 
> Ignoring the unintended Annex B issue, that failure supports my point. In ES5 we could not have failed at this point, because this point is only reached if allegedDate is a genuine Date.
> 
>  
> 
> See http://people.mozilla.org/~jorendorff/es6-draft.html#sec-date.prototype.getyear step 1 and the definition of "this time value" in http://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-date-prototype-object 
> 
> (BTW, did you intentionally pick an Annex B Date method?)
> 
> Allen
> 
> 
> 
> -- 
>     Cheers,
>     --MarkM

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150122/8704c355/attachment.html>


More information about the es-discuss mailing list