Re: Proposal: Boolean.parseBoolean
The user's code… Trying to parse "" will also throw with JSON; !!"false " is true; host objects (or whatever they're called now) such as document.all. Unsubscribing. Not sure why I didn't earlier… I need to stay a code-free user. :-) On Thu, Mar 16, 2017 at 7:08 PM, 段垚wrote: > > > 在 2017/3/17 5:03, Ben Newman 写道: > > Just to check my understanding, would > > Boolean.parseBoolean = function (value) { > return !! (value && JSON.parse(String(value))); > }; > > be a reasonable polyfill for your proposed function? > > This implemention throws for invalid JSON syntax and is case-sensitive > (Java's counterpart is case-insensitive). Is this better? > ``` > Boolean.parseBoolean = function (value) { > return !(!value || /^false$/i.test('' + value)); > }; > ``` > > However I'm not sure this is widely useful. If the value is not from JSON, > there are a lot of alternatives for 'true|false', e.g. 'yes|no', 'on|off', > or 'T|F', and different rules for casing/empty value/invalid syntax. So > it's better to do this in users' code. > > > > This would definitely be useful for parsing `process.env.*` environment > variables in Node! > > Ben > > On Thu, Mar 16, 2017 at 4:55 PM Dmitry Soshnikov < > dmitry.soshni...@gmail.com> wrote: > >> Similar to `Number.parseInt`, the `Boolean.parseBooelan` might be useful >> for "boolean strings" retrieved from some string-based storages, which do >> not support other types at serialization. >> >> ``` >> Boolean.parseBoolean('true'); // true >> Boolean.parseBoolean('false'); // false >> ``` >> >> This is to contrast current: >> >> ``` >> Boolean('false'); // true >> ``` >> >> In JS people do today: >> >> ``` >> let shouldRefresh = (data.shouldRefresh === 'true'); >> ``` >> >> Other parsing results: >> >> ``` >> Boolean.parseBoolean('1'); // true >> Boolean.parseBoolean(1); // true >> Boolean.parseBoolean(); // true >> Boolean.parseBoolean(true); // true >> >> // Falsey: >> Boolean.parseBoolean('0'); // false >> Boolean.parseBoolean(''); // false >> Boolean.parseBoolean(false); // false >> ``` >> >> The API, and the results are from Java's corresponding >> `Boolean.parseBoolean` method: https://docs.oracle. >> com/javase/7/docs/api/java/lang/Boolean.html# >> parseBoolean(java.lang.String). >> >> Dmitry >> ___ >> es-discuss mailing list >> es-discuss@mozilla.org >> https://mail.mozilla.org/listinfo/es-discuss >> > > > ___ > es-discuss mailing > listes-discuss@mozilla.orghttps://mail.mozilla.org/listinfo/es-discuss > > > > ___ > es-discuss mailing list > es-discuss@mozilla.org > https://mail.mozilla.org/listinfo/es-discuss > > -- Garrett Guitar Videos https://www.youtube.com/channel/UCY_uK9hur86KEuiG8s7yvWw @xkit ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Function#toString revision: JSDoc comments?
On Sat, Apr 16, 2016 at 7:53 AM, Caitlin Potterwrote: > How would that interact with angular.js' Function.prototype.toString > parsing? Seems like doing that could break some content, even if it were > useful > Comments are generally a failure of the developer to write self explanatory code. The proposal to break Angular.JS by having Function.prototype.toString result in preceeding comments could send a message of not relying on Function decompilation (we went over this in 2005; a dead horse), but it won't happen. Because although code in the wild (for the web) cannot reasonably expect Function.prototype.toString to produce anything other than a string for which eval will throw a SyntaxError, implementations try to meet the unreasonable demands imposed by these libraries and their hapless users (the coders who use Angular in their source code, not the end user). Not only does it contradict existing spec (something the Angular.js developers obviously didn't bother to read), but it changes what browsers actually do, and if it means breaking the web, browsers won't do that. Even if the vast majority of content served in conjunction with Angular is not useful. Thank you, -- Garrett Guitar Videos https://www.youtube.com/channel/UCY_uK9hur86KEuiG8s7yvWw @xkit ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: How to modify the scope chain without `with` ?
On Mon, Feb 15, 2016 at 1:13 AM, Coroutineswrote: > This post might be overly wordy. Sorry. It relates to the > functionality provided by the `with` keyword and why I think it's > important in the future. > > I am currently rewriting a templating module that I think is very > useful for it's ability to turn a function in coffeescript syntax into > a sort of DSL - something that looks like this: > > template = -> > doctype 5 > html -> > head -> > title @title > body -> > div id: 'content', -> > if @posts? > for p in @posts > div class: 'post', -> > p p.name > div p.comment > form method: 'post', -> > ul -> > li -> input name: 'name' > li -> textarea name: 'comment' > li -> input type: 'submit' > > For those not familiar with Coffeescript, "= ->" creates a function > with no arguments, the indented sub-block is the body of the function. > > All of these things essentially compile into nested functions like: > html(head(title(this.title)) > > (not an exact translation) > > Anyway, this library/module called (ck) exploits the little-used > `with` keyword. It creates a function like this: > > function (scope, template) { with (scope) { template(); } } > > So the template is just a series of functions that lookup within > `scope` for a function creating HTML. The problem is this module > (imo) wastefully creates a lot of closures to create the HTML tags. > I think you'll have a lot better luck starting out like I did: Learn HTML first. You're working on some complicated stuff there, and for me, I always try to get simple to work. Simple and working is good! You cannot have too solid of a grasp of HTML. Ditto for CSS. When it comes to javascript, context and scope can be tricky and confusing for those coming from other languages. Thank you, -- Garrett @xkit ChordCycles.wordpress.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: JavaScript Language feature Idea
On Sat, Jan 23, 2016 at 12:46 PM, kdexwrote: > @Michał: That really depends on the point of view: If you need zero-based > indexing from the right, as `[]` does from the left, you'd use > `Array.prototype.last`. > > On Samstag, 23. Januar 2016 20:56:02 CET Michał Wadas wrote: >> I can't consider `.last(1)` method to be readable... >> But I think `.nth(n)` method with support for negative index would be >> really useful. >> you can also slice from the end of an array: var a = [1,2,3,4]; // Get the second-to-last item. a.slice(-2,-1) A method to find an item at a given index could be designed. a.itemAt(-2); I trimmed the rest. I have enough difficulty with advanced GMail view. I can't get back to Basic HTML view as default. Top posting makes editing a lot harder in GMail Advance View. Plus it auto-saves on every undo/redo, and coupling that with El Capitan, and it's all so slow and clunky. So I didn't fix yuour top post completely. Because I'm saving my energy up for figuring out how to paste into youtube comments. Man, this web stuff, google… so cutting edge. Wow! -- Garrett @xkit ChordCycles.wordpress.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Confusion with Object.prototype.toString and primitive string datatype
Because javascript is dynamically typed, conversion from objects to primitive values and vice versa. This is done respectively by the internal [[ToPrimitive]] and [[ToObject]] methods. See Object.prototype.toString, step 3 | Let O be ToObject(this value). http://people.mozilla.org/~jorendorff/es6-draft.html#sec-toobject ToObject, creates a String object whose value is that of the passed-in string: Thank you, On Fri, Jan 1, 2016 at 9:24 AM, Arup Rakshitwrote: > Hi, > > Consider the below simple code : > > 'k' instanceof String; // false > new String('k') instanceof String; // true > > Now, When I am inspecting them as below why in both cases the output comes as > [object String] ? > > The below is understood as per the result of the `instanceof` operator. > > Object.prototype.toString.call( new String('k') ); // "[object String]” > > My confusion comes when I see the below code output : > > Object.prototype.toString.call( 'k' ); // "[object String]” > > Can anyone please explain it ? > ___ > es-discuss mailing list > es-discuss@mozilla.org > https://mail.mozilla.org/listinfo/es-discuss -- Garrett @xkit ChordCycles.wordpress.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Maven like dependency management for browsers
On 8/7/15, Behrang Saeedzadeh behran...@gmail.com wrote: Hi Sebastien, Guys — On Sun, Aug 2, 2015 at 10:38 PM Sébastien Cevey seb.ce...@guardian.co.uk wrote: [...] Versions can be specified either at the top-level config, or even at the import level, e.g.: System.import('npm:lodash@3.10.0').then(function(_) { console.log(_.max([1, 2, 3, 4])); }); That looks like the client (browser) would need to fetch the dependency list and mapping? Declarative chain of responsibility pattern was proposed years ago. The idea is different: It works more like ANT targets, where dependencies are declared right there in the document itself. The thread got some noise and then it died. script src=fabric.js async id=fabric script depends=fabric alert(loaded!); /script -- Garrett @xkit ChordCycles.wordpress.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Can't do push in forEach
On 5/14/15, Emanuel Allen emanuelal...@hotmail.com wrote: Surprise that I can't do arr1.forEeach(arr2.push); Check that line more carefully. Will throw an error. Using bind as: push = arr2.bind(push); Arrays don't have a bind method. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: let function
On 5/14/15, Alexander Jones a...@weej.com wrote: Ah, thanks for explaining! What about the Temporal Dead Zone of let, or const binding semantics, for those of us who are obsessive enough to desire that kind of thing everywhere? Let a constructive discussion about this proposal take place. The specification, can most reasonably be taken among programmers to mean the latest version of specification not draft specification or proposal. Evangelists and standards geeks tend to miscall draft specification to the misfortunate effect that it misleads developers into believing that drafts are normative, final, etc. That's quite a bit worse than the abrasiveness and confusion seen here, but hopefully they can stop and a discussion can take place. http://www.ecma-international.org/ecma-262/5.1/#sec-12 Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. The decision for such wording probably came from discussions and time constraints of getting ES5 done. The problem of FunctionDeclaration arose from implementations in JScript (see [MS-ES3EX] and language extensions in Spidermonkey and others. It progressed to misstatements in presentations and books. For more on this, see Named function expressions demystified. On Thursday, May 14, 2015, Bergi a.d.be...@web.de wrote: Alexander Jones schrieb: On Thursday, May 14, 2015, Domenic Denicola d...@domenic.me wrote: They can, in fact, be scoped in a for loop. That's not what I see, in strict mode at least, which I assume most people consider de facto by now! From V8: SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function. That's ES5. In ES6, function declarations are allowed in blocks - with the new block scope semantics. This was only possible as ES5 strict mode held that spot open so now it doesn't break anything :-) Yes, it will need a while until people get accustomed to that. Bergi ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: let function
On 5/14/15, Kevin Smith zenpars...@gmail.com wrote: Good points. All the more reason to throw out declarations as statements in favour of let/const/var, which we all have to understand well anyway, for other types of variable. Declarations aren't going anywhere, Getting rid of FunctionDeclaration was not proposed. If the proposed `let function` idea is no good, is it because FunctionDeclaration-as-a-Statement is a better replacement? Or is there a better reason? and there is zero interest in deprecating them. You might want to spend a bit more time learning the spec or lurking before making proposals. You go read the spec and lurk. Hope that helps. It obviously doesn't help at all. Consistency in implementations would help. An easier-to-read ECMAScript specification would also help. Discussions like this can help when they point out the reality of what implementations do vs what the specification and its authors say vs what the so-called experts, and worse (W3Schools, etc) say. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Declaration binding instationationing
OK, here is a bug report: Bug 4336 - 10.5 Declaration binding instantiation https://bugs.ecmascript.org/show_bug.cgi?id=4336 On 4/29/15, Mathias Bynens mathi...@opera.com wrote: On Wed, Apr 29, 2015 at 7:29 AM, Garrett Smith dhtmlkitc...@gmail.com wrote: There is an English problem here: Let existingProp be the resulting of calling the [[GetProperty]] internal method of go with argument fn. s/resulting/result/ indeed. Can the spec be made easier to read? FYI, the best way to go about this is to file a spec bug on https://bugs.ecmascript.org/ under the editorial issue component. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Declaration binding instationationing
There is an English problem here: Let existingProp be the resulting of calling the [[GetProperty]] internal method of go with argument fn. Can the spec be made easier to read? -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: super() on class that extends
On 4/10/15, Axel Rauschmayer a...@rauschma.de wrote: The reason why you need to call the super-constructor from a derived class constructor is due to where ES6 allocates instances - they are allocated by/in the base class (this is necessary so that constructors can be subclassed that have exotic instances, e.g. `Array`): Can you please explain how extending Array works. Also what is the optional identifier optional for in ClassExpression: var myArray = (new class B extends Array { constructor() { super(1,2,3,4,5); } }); alert(myArray.length); // it's 0 in Babel. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Accepting an array as the first parameter to String.prototype.includes
On 3/10/15, Edwin Reynoso eor...@gmail.com wrote: Hi Edwin - Well the current ES6 `.includes()` was before named `.contains()`: [String.prototype.includes] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#String.prototype.contains ) But if Garrett Smith was trying to point out that `.contains()` would be better naming for the specific purpose of using an Array: `str.contains([Mary, Bob])` then ok? maybe. str.contains was Andrea's interpretation of my example. Nevermind that; let me try again... You first asked about making String.prototype.includes take an array, check every item in the array, and return false if any array item is not present in the string, else return true. From that, you switched it around to array.every, to make sure every item was in the string. names.every(name = str.includes(name)); So far so good... That's essentially what Array.prototype.containsAll would do. Array.prototype.containsAll(anotherArray) You can split the string to get anotherArray. names.every(str.split(/,\s*/)); I cannot explain what ES6 @@split does. The spec have gotten even farther away from how web developers understand the language. The ECMAScript specification has always been complicated by internal specification mechanisms, and it was because of this obfuscation that I was able to have a bit of an edge on others. I was able to understand the difference between the confusingly same-named [[Prototype]] (an object's internal property) and fn.prototype (the property that every user-defined function gets by default), and that there implies that each user-defined function has both a [[Prototype]] (being Function.prototype) and a .prototype property. It's confusing, but I got it. The new stuff in the spec, where there is not even String.prototype.split, but @@split is hard to understand. The ECMAScript 3 spec was already too hard for most developers. Things like missing RegularExpressionLiteral, the ActivationObject/VariableObject (which one is it?), PrimitiveValue being a number for Date objects, but where addition calls ToPrimitive with hint string, and that gets passed to DefaultValue. It's hard. We need to work for the tech companies that steal your data and provide useless junk to the user. Call us rockstars or other insulting titles, but at the end of the day, I need to to is memorize those specs if I want to understand what I am doing in order to pay my rent. It can and should suck less. ECMAScript 5 added complexity. ECMAScript 6's explanations and specification terminology seems too much for me. The spec shouldn't be so hard that programmers can't understand it. A good spec should serve as a reference for developers to go and look up how it works. I can't say how I'd write it better because I haven't taken the time to grok it all. Nor do I plan to - life is too short. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Accepting an array as the first parameter to String.prototype.includes
On 3/10/15, Garrett Smith dhtmlkitc...@gmail.com wrote: On 3/10/15, Edwin Reynoso eor...@gmail.com wrote: [...] specs if I want to understand what I am doing in order to pay my rent. It can and should suck less. Let me rephrase that: I don't mean that the specification sucks - sitting down and trying to figure it out; reading the spec, for me, is not enjoyable work. The spec is hard and frustrating. But I really do appreciate all the hard work and effort by Brendan, Allen, etc - you guys are all a lot smarter than I am. And ECMAScript is making a lot of improvements. But I still don't like reading the spec. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Accepting an array as the first parameter to String.prototype.includes
On 3/10/15, Andrea Giammarchi andrea.giammar...@gmail.com wrote: I'm still having hard time understanding what's the difference between contains and the good old indexOf beside the RegExp check ... but I agree having multiple explicit searches instead of multiple implicit searches won't make such big difference. Good news is, you probably will still use RegExp anyway because names can be composed and haveing a \bName\b helper is probably what you might need anyway :-) i.e. Maria !== Marianne What if Array had a contains or containsAll functions? var s = Maria, Mariana; var a = s.split(/\s*,\s*/); [Maria, Mariana].every(e={return a.indexOf(e)!=-1}); true But a `contains` function might be better than indexOf [Maria, Mariana].every(e={return a.contains(e)}); But `containsAll` might be even better. a.containsAll([Maria, Mariana]) seems even easier to read for me. There is already `filter` for exclusions. What about merging arrays? Array.union(array2, array3, ...); On Tue, Mar 10, 2015 at 3:31 PM, Bergi a.d.be...@web.de wrote: Edwin Reynoso wrote: There are times where I would like to check whether a string has every occurrence of certain strings/numbers: Now to achieve what I would like `String.prototype.includes` to accomplish with an array as the first parameter, I currently take the following approach: var str = John,Mary,Bob,Steve; var names = [Mary, Bob]; names.every(name = str.includes(name)); // true; And that's perfectly fine imho, pretty expressive about what is done about the array. Just passing an array to `.includes` is rather meaningless (not denotative). If we need a method to do this (to allow for native optimisations with fancy string search algorithms), I'd suggest to use a different method name like `String.prototype.includesAll`. Bergi ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Accepting an array as the first parameter to String.prototype.includes
On 3/10/15, Andrea Giammarchi andrea.giammar...@gmail.com wrote: contains better than indexOf ? I'd agree only if contains wasn't accepting any extra argument, which makes it even more (pointless?) similar to indexOf. If it had only one incoming parameter, you could have `[maria, marianne].some(str.contains, str)` and win over all other examples. but just the `!=-1` or `-1` as reason to prefer contains? ... dunno, I think I have 99 problems in JS related development, `-1` ain't one :-/ Evidently. I can only guess that str is a string. Strings don't have a contains method, nor was one proposed the call str.contains(str) inside of a call to some looks like a confused mistake. -- Garrett @xkit ChordCycles.com garretts.github.io personx.tumblr.com ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Proposal: Additional Meta Properties for ES7
Can you show an example of how callee is used with a fat arrow function? (()={alert(callee);})() Thanks. On 2/26/15, Allen Wirfs-Brock al...@wirfs-brock.com wrote: Here is a new proposal for some additional meta properties that should be considered for ES7 https://github.com/allenwb/ESideas/blob/master/ES7MetaProps.md I've added this to the agenda for next months TC39 meeting but pre-meeting discussion is always welcomed right here. Allen -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: JavaScript 2015?
On 1/22/15, Brendan Eich bren...@mozilla.org wrote: Andrea Giammarchi wrote: agreed and not only, it took years before various engines fully implemented ES5 so saying years later that an engine is fully compliant with a year in the past feels so wrong !!! Why is that? Where is the thread that explains this decision? I mean ... how should I call my browser that is not 100% compliant with HTML5, a fully compliant HTML 1997 browser ? Of course this question arose with respect to HTML5, which was nowhere near done (is it yet?) before marketeers at browser vendors started touting compatibility and various players hyped the orange shield. (And then Hixie said it was a living spec, version-free. :-P) HTML5 isn't going to be done. I wrote, extensible design doesn't have a due date, someone else coined living standard, and that sealed it in. EcmaScript differs from HTML5 obviously in that it defines the syntax, including new syntax features like spread, modes (strict and non-strict), and internal specification methods like [[ToPrimitive]] new internal methods like [[NeedsSuper]]. Syntax features are more complex than new built-ins (or any new host objects of HTML5) because they affect the language itself and all of its dependencies, internal and external. Language modes increase this complexity. Modularity can make when is it going to be done less of an issue. I don't see how modules could be used for new syntax features (they possibly could be; I just don't see how). But speaking of the orange shield, what about a sticker for HTML4 with It works as a tagline? -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Proposal: Syntax sugar for single exit and early exit functions.
On 11/16/14, Biju bijumaill...@gmail.com wrote: [...] Proposal: I wish there was some syntax sugar like function someClickHandler(){ doStuff(); doAnotherStuff(); doYetAnotherStuff(); } finally { return false; } function rf() { try { throw-an-error; } finally { return false; } } rf(); // false -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Having a non-enumerable Array.prototype.contains may not beweb-compatible
Old sites with old version of Mootools will have problems when trying to use native Array.prototype.contains. Is that the only problem or is there something else I'm missing? On 10/7/14, Andrea Giammarchi andrea.giammar...@gmail.com wrote: FYI: from a MooTools core developer: https://gist.github.com/fakedarren/28953b01e455078fb4f8 The article has a few issues. Array.prototype.forEach landed in Mozilla before 2006, and there are still libraries that modify DOM prototypes. Polymer, by the former Bindows author, is one. Modifying built-in Array.prototype for GP scripts was never a good idea. And the gist misses the big point that modifying objects that you don't own, you risk issues with forwards compatibility. Here it is now, at forward compatibility issue point. The ideas were bad at the time. I criticized them pretty heavily around 2007 for these ideas and they complained on my blog. Now, they are congratulating themselves on their efforts, and blaming Microsoft for forcing them to make those mistakes. Mootools' contains be refactored and that's what the good folks at this thread brought up. MooTools can do a conditional check with a feature test, create a replacement alternative for their own methods, and deprecate, for future removal, MooTools' custom Array.prototype.contains in favor of something that is not incompatible. This situation reminds me of the W3C proposal for Event creation to use `Event` constructor, regardless of Mootools already having defined a global Event constructor for the web. That w3c proposal was adopted and implemented, probably with compat issues, seeing as MooTools has removed their Event for their new global DOMEvent function, deprecated their global `Event` function, kept it for backwards compatibility, and then removed it in a subsequent release. Their replacement's name DOMEvent starts with DOM and there is no guarantee that the w3c won't define a new type of event called DOMEvent (maybe to describe DOM Mutation). MooEvent is a more intentional and a better name. But anyway, MooTools, can with their Array.prototype.contains what they did with their Event. Maybe with a better name or maybe using another typeof approach than rename. jsfiddle.com http://lists.w3.org/Archives/Public/public-script-coord/2011JulSep/0115.html http://www.twitlonger.com/show/bd2994 -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: use strict VS setTimeout
On 9/7/14, Domenic Denicola dome...@domenicdenicola.com wrote: I don't understand why this is any more surprising than any other function that calls its callback with .call(something). It doesn't matter whether the callback is strict or not; .call(window), which is what the spec does, will override it. As far as I can see this issue has absolutely nothing to do with strict vs. sloppy. I agree on that point; setTimeout passes the window to the callback as the this value. But that has nothing to do with inheritance. Method setTimeout uses the global object as the `this` value for the callback function, much like addEventListener, etc, as does `.call(window)` like you mentioned. From: Andrea Giammarchimailto:andrea.giammar...@gmail.com Sent: 2014-09-07 19:14 To: Mark Millermailto:erig...@gmail.com Cc: Mark S. Millermailto:erig...@google.com; es-discuss listmailto:es-discuss@mozilla.org Subject: Re: use strict VS setTimeout It feels to me also a vector that will happily pass all linters and code analyzers giving users a door to reach native context and start playing in there with everything else. I'm pretty sure you would agree on this too :) Please let us know if there's any follow up, it's probably easier/faster if some googler mention this issue to other googlers that are collaborating with WHATWG or W3C or both (or none) Thanks On Sun, Sep 7, 2014 at 7:11 PM, Mark Miller erig...@gmail.commailto:erig...@gmail.com wrote: On Sun, Sep 7, 2014 at 11:07 AM, Andrea Giammarchi andrea.giammar...@gmail.commailto:andrea.giammar...@gmail.com wrote: Yes Axel, that's how it works, this will show undefined indeed all over ```js (function () { 'use strict'; function g() { console.log(this); } g(); // undefined setTimeout(function () { g(); // undefined }, 0); }()); ``` or testing other use strict restrictions: ```js (function () { 'use strict'; setTimeout(function () { argument.callee }, 0); }()); ``` The strict behavior is preserved, it's not an opt-out, but the invoked function within setTimeout has the global context regardless it has been defined under the strict directive + regardless it defines itself as strict. Basically if you feel secure about use strict here you have a case that shows you shouldn't ... making one point of strict directive kinda broken/pointless. Agreed. I would remove only kinda from that statement ;). Regards On Sun, Sep 7, 2014 at 7:02 PM, Axel Rauschmayer a...@rauschma.demailto:a...@rauschma.de wrote: On Sep 7, 2014, at 19:47 , Mark S. Miller erig...@google.commailto:erig...@google.com wrote: On Sun, Sep 7, 2014 at 10:36 AM, Mathias Bynens mathi...@opera.commailto:mathi...@opera.com wrote: On Sun, Sep 7, 2014 at 7:29 PM, Andrea Giammarchi andrea.giammar...@gmail.commailto:andrea.giammar...@gmail.com wrote: This looks like a potential problem when possible passed methods are not bound + it looks inconsistent with *use strict* expectations. Yes. This looks like a typical screwup. Thanks for pointing it out. Interesting. Follow-up question: isn't strictness propagated lexically? That is, shouldn't the parameter of `setTimeout()` be strict even without being explicitly declared as such? -- Cheers, --MarkM -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: use strict VS setTimeout
On 9/7/14, Mark Miller erig...@gmail.com wrote: On Sun, Sep 7, 2014 at 11:27 AM, Domenic Denicola dome...@domenicdenicola.com wrote: I don't understand why this is any more surprising than any other function that calls its callback with .call(something). The issue is what the something should be, and which choices for something are surprising for what APIs. It doesn't matter whether the callback is strict or not; .call(window), which is what the spec does, will override it. I don't understand what you're trying to say here. What will override what? As far as I can see this issue has absolutely nothing to do with strict vs. sloppy. As Andrea initially stated, this is a DOM-spec issue, not a JS issue, in that JS allows setTimeout to call the callback with WTF it wants. However, the purpose of setTimeout, etc, from the JS programmer's perspective, is to postpone some action to some future time. From this understanding, there's no reason to give the postponed action access to the global object. From a POLA perspective, there is thus strong reason not to. If legacy compatibility is needed then setTimeout's callback function must be called with the same window of setTimeout, just as with global addEventListener. script use strict addEventListener(click, function(ev){ console.log(this === window); }); /script -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: use strict VS setTimeout
On 9/7/14, Andrea Giammarchi andrea.giammar...@gmail.com wrote: **implicitly fail** from a user point of view that used use strict to avoid receiving the global context in there ... I am not sure how much you want to turn it back to me but you are missing the point and I've not much else to say. use strict doesn't avoid receiving the global object. For function calls in strict code, use strict says the `this` value is supplied by the caller, but if it isn't, the `this` value is undefined. The caller of the callback your example below was setTimeout. Method setTimeout maintains a reference to the window and calls callback function, `a`, with the window as the thisValue. setTimeout( function a() { console.log(this); }, 1); -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: use strict VS setTimeout
On 9/7/14, Andrea Giammarchi andrea.giammar...@gmail.com wrote: this is getting nowhere ... yeah Garret, you can use `.call` and we all know that ... Now I want you to answer this: why on earth would you expect a global context in a setTimeout or setInterval operation for a function/method you have explicitly defined as strict ? One single use case ... do you have it ? 'cause you don't use use strict inside method/functions passed to `addEventListener` as example, do you? So I will close the loop with the very initial snippet and just one extra comment ```js (function () { 'use strict'; // == as a developer, I don't want implicit window setTimeout(function () { 'use strict'; // == as a developer, I don't want implicit window console.log(this); // [window/global Object] // SO WHY ON EARTH I HAVE AN IMPLICIT window HERE ? }, 0); }()); ``` setTimeout is explicitly calling your callback with the window. It's specified to do so in HTML5. It is a little strange. Should HTML5 be changed? http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#dom-windowtimers-settimeout -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Exotic OBJECT?
On 8/12/14, Allen Wirfs-Brock al...@wirfs-brock.com wrote: On Aug 12, 2014, at 7:52 PM, Garrett Smith wrote: On 8/12/14, Allen Wirfs-Brock al...@wirfs-brock.com wrote: On Aug 12, 2014, at 2:17 PM, Garrett Smith wrote: On 8/12/14, Allen Wirfs-Brock al...@wirfs-brock.com wrote: [...] As long as addEventListener is implemented as a built-in function (whatever that means for the implementation) then f.p.toString should be able to deal with it. Now built in is overloaded. Built in objects are those which are supplied the ECMAScript implementation, independent of the host environment. A built in function is a built-in object that is a function. Method addEventListener is supplied by the host environment and is therefore not a built-in function. The new meaning for built-in function that you mention doesn't match the term defined earlier in the spec: built in object. The built-in function objects defined in this specification may be implemented as either ECMAScript function objects (9.2) whose behaviour is provided using ECMAScript code or as implementation provided exotic function objects whose behaviour is provided in some other manner. That looks like an attempt to describe functions that are implemented with native code, as described by CreateBuiltinFunction. CreateBuiltinFunction might be better named, such as CreateNativeFunction, to provide consistent, unambiguous terminology and which could also be used unambiguously for WebIDL platform objects. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Exotic OBJECT?
What's the explanation and reason for this strange characteristic of the OBJECT element in Firefox? Firefox 31: typeof document.createElement(object) function Function.prototype.toString.call(document.createElement(object)); TypeError: Function.prototype.toString called on incompatible object If the typeof OBJECT results function then it either: a) implements [[Call]] or b) is exotic Since calling `Function.prototype.toString` with OBJECT as the this value results in a TypeError, it appears that the OBJECT does not implement [[Call]] and thus the only explanation is that the OBJECT is exotic. Did I get that right? Or is there another explanation? What's the explanation and reason for this strange characteristic of the OBJECT element in Firefox? -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Exotic OBJECT?
On 8/12/14, Claude Pache claude.pa...@gmail.com wrote: Le 12 août 2014 à 18:44, Garrett Smith dhtmlkitc...@gmail.com a écrit : What's the explanation and reason for this strange characteristic of the OBJECT element in Firefox? Firefox 31: typeof document.createElement(object) function Function.prototype.toString.call(document.createElement(object)); TypeError: Function.prototype.toString called on incompatible object If the typeof OBJECT results function then it either: a) implements [[Call]] or b) is exotic Since calling `Function.prototype.toString` with OBJECT as the this value results in a TypeError, it appears that the OBJECT does not implement [[Call]] and thus the only explanation is that the OBJECT is exotic. Did I get that right? Or is there another explanation? What's the explanation and reason for this strange characteristic of the OBJECT element in Firefox? According to comments 10-18 in https://bugzilla.mozilla.org/show_bug.cgi?id=268945 , object and embed elements do implement [[Call]] for some obscure reason. Hence `typeof` yielding function. Maybe I'm splitting hairs, but the spec doesn't say explicitly that all objects implementing [[Call]] must support `Function.prototype.toString`, although I'm not sure that that omission was intentional. Anyway, if you want to test if an object implements [[Call]], the best method is simply to try to call it: document.createElement(object)() Calling the OBJECT here does not result in a TypeError. If it were not callable, then TypeError would have to be the result. Thus, the OBJECT implements [[Call]]. Furthermore, the ReferenceError that is thrown as a result of calling Function.prototype.toString on that OBJECT is not explained by the OBJECT not implementing call. To test if a function implements [[Call]], use the typeof operator. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Exotic OBJECT?
On 8/12/14, Allen Wirfs-Brock al...@wirfs-brock.com wrote: Allen - On Aug 12, 2014, at 9:44 AM, Garrett Smith wrote: What's the explanation and reason for this strange characteristic of the OBJECT element in Firefox? Firefox 31: typeof document.createElement(object) function Function.prototype.toString.call(document.createElement(object)); TypeError: Function.prototype.toString called on incompatible object If the typeof OBJECT results function then it either: a) implements [[Call]] or b) is exotic Since calling `Function.prototype.toString` with OBJECT as the this value results in a TypeError, it appears that the OBJECT does not implement [[Call]] and thus the only explanation is that the OBJECT is exotic. Did I get that right? Or is there another explanation? I based this conclusion off of the latest ES6 draft, at: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-function.prototype.tostring throws a TypeError exception if its this value does not have a [[Call]] internal method What's the explanation and reason for this strange characteristic of the OBJECT element in Firefox? I don't see any where in your test where you [[Call]] OBJECT. I tested the typeof operator to see if the OBJECT implements [[Call]] by using typeof. The result was function. Please go back and read all replies. You [[Call]] Function.prototype.toString with OBJECT passed as the this value. The ES5 spec. clearly says that F.p.toString is called with a this value that is not a Function object. Note this usage of Function object means an actual instance of the built-in Function constructor and not the more general, any object that isCallable. ES5, in a few places, vascillates between the terms function object and isCallable. E.g. When the [[Call]] internal method for a Function object... yet there is no description of what happens when [[Call]] is called on any object that implements [[Call]] but is not a function (non-function host objects). Such objects not only exist but are mentioned under the definition of the typeof operator:- Object (implements [[Call]]) function There is also the failure of ES5 to differentiate between the two types of host objects: native, and non-native, as I brought up and as we discussed over 4 years ago. This differentiation is explained in the ES6 draft as exotic objects. The ES6 replaces function object with isCallable and implements [[Call]] in many places, and the place that is of concern here is the description of Function.prototype.toString: | Function.prototype.toString | ... | | The toString function is not generic; it throws a | TypeError exception if its this value does not have | a [[Call]] internal method. Therefore, it cannot be | transferred to other kinds of objects for use as a method. Do you agree or disagree with the fact that the OBJECT implements [[Call]]? And if you disagree, please explain. Are you proposing that the definition of Function.prototype.toString needs to be reverted to once again use function object? If not, what is your proposal? -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Exotic OBJECT?
On 8/12/14, Allen Wirfs-Brock al...@wirfs-brock.com wrote: On Aug 12, 2014, at 2:17 PM, Garrett Smith wrote: On 8/12/14, Allen Wirfs-Brock al...@wirfs-brock.com wrote: [...] | Function.prototype.toString | ... | | The toString function is not generic; it throws a | TypeError exception if its this value does not have | a [[Call]] internal method. Therefore, it cannot be | transferred to other kinds of objects for use as a method. This is a spec, bug. should probably be expressed as does not have a [[Code]] internal slot. What is the [[Code]] for host methods like addEventListener? And what is the expected result of addEventListener.toString()? Spec for Function.prototype.toString has never reflected reality for host methods. Thanks. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Array.prototype.contains
On 7/24/14, Andrea Giammarchi andrea.giammar...@gmail.com wrote: What is this about? Not an answer nor a solution to what I've said... Just think that NaN is rarely an explicit value, rather something potentially generated at runtime. Would you .some(Number.isNAN.bind(Number)) all the Arrays? I don't think so, at least I wouldn't It looked like you were trying to determine if a finite number is in an array. Is that right? That answer to how to do that would be: Number.isFinite(v) arr.indexOf(v) != -1; -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Array.prototype.contains
On 7/23/14, Maël Nison nison.m...@gmail.com wrote: Isn't replacing DOMStringList a different issue than adding Array.prototype.contains ? Using indexOf is possible, but a .contains() method would give a stronger notice of intent when reading code. So too, for cases of removing an item, would Array.prototype.remove(v) show clear intent. On 7 March 2014 15:11, Boris Zbarsky bzbar...@mit.edu wrote: On 3/6/14 6:15 PM, Joshua Bell wrote: FWIW, Blink uses DOMStringList only in IndexedDB and apparently in Location.ancestorOrigins Indeed. And Location.ancestorOrigins is fairly new and not broadly implemented, so I don't expect its behavior to be a strong compat constraint. So I guess that leaves us with a few questions: 1) Is it still early enough in the indexeddb world that we can change the thing it uses from DOMStringList to Array. And if so whether that's a change we want to make. 2) If we want to keep the non-writing behavior for indexeddb or for some other reason (insufficiently flexible bindings systems?) can't switch ti to Array for now, can we just remove item() and contains() from DOMStringList to make the switch easier later? -Boris ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss -- Maël Nison (arcanis https://twitter.com/arcanis) Frontend Developer @ Sketchfab -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Array.prototype.contains
On 7/23/14, Andrea Giammarchi andrea.giammar...@gmail.com wrote: agreed, already imagining loops like ```js while (arr.contains(value)) arr.remove(value); ``` although that looks a bit nicer than ```js var i; while (-1 (i = arr.indexOf(value))) arr.splice(i, 1); ``` my main concern about `.contains()` is its potentially un-optimal implementation and error prone logic. Most of the time we want to know if an array contains something to avoid duplicated because we are missing `.unique()` ```js if (!arr.contains(obj)) arr.push(obj); ``` Most other times we want to do some action with that contained value or its index and here we have a redundant and error prone cases: ```js if (arr.contains(obj)) { // need the index anyway var i = arr.indexOf(obj); // but this might fail // splice or do other things ... } ``` AFAIR the latter `.contains()` does not suffer same problems `.indexOf()` does and this will result in incompatible operations with array indexes, assuming contains told us we are good to go. As example, `.contains(NaN)` can cause disaster-prone logics if followed by `.indexOf(NaN)` because the first check will tell the developer at runtime for sure something was there while the second check will return a lovely -1 most likely unexpected inside the block that believe `.contains(value)` was a safe bet. // Contains NaN: [1, NaN, ].some(function(e) {return Number.isNaN(e);}) -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: TC39 vs the community
Nice. I wonder what Horse would think of Vermin Supreme's pony identification program. But in all seriousness, Google, MSFT, are all pushing for IoT or wearables by putting on events featuring that, creating a buzz, and making press on the event. On 6/23/14, Brendan Eich bren...@mozilla.org wrote: +1 But Garrett's post was helpful in its own way. @horse_esdiscuss agrees! /be joe wrote: And here I thought you were making an educated argument with your explanation of the history of propaganda and public relations. When I first read corporate propaganda, I thought you mean the propaganda of JS developers, not commercial corporations. Frankly, I find the idea that commercial interests trump corporate identity hard to fathom. If that were true, Java would be a very different language today, and JavaScript would have long fallen into disuse. The community, very much exists; it's not a figment of some PR type's imagination. Anyone claiming there isn't a sense of corporate identity among JS developers is fooling themselves. I'm on the side of TC39, by the way. I don't believe in democracy in software. That's why we have standards organizations. Joe -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: TC39 vs the community
On 6/23/14, joe joe...@gmail.com wrote: And here I thought you were making an educated argument with your explanation of the history of propaganda and public relations. When I first read corporate propaganda, I thought you mean the propaganda of JS developers, not commercial corporations. Frankly, I find the idea that commercial interests trump corporate identity hard to fathom. So you agree, then. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: TC39 vs the community
On 6/20/14, David Bruant bruan...@gmail.com wrote: Hi, I'm not quite sure what this is all about, so forking in hope for clarifications. I'm sorry to send a message that will probably be read as noise by a lot of people, but I'm also tired of some of these pointless and unconstructive, if not destructive, fights among people (in here, on Twitter or elsewhere). I hope to have a conversation to start the end of the alleged unharmonious relationship between TC39 and JS developers. Domenic, your email suggests a fairly strong dichotomy between TC39 and the community. As far as I'm concerned, to begin with, I don't see anything that is called the community in JavaScript. Words tend to get coopted and their meanings stretched to suit agendas. aside If you're easily offended, or if you wish not to read opinionated information, stop reading now. Also, I add nothing whatsoever to the technical matter of this discussion. /aside Developer relations is public relations for developers, and public relations is propaganda. This is because Edward Bernays used a propaganda technique to rename propaganda to Public Relations.It stuck. The renaming of term propaganda was necessary because it had lost any acceptibile legitimacy that it had maintained prior its use in WWII, when Joseph Goebbels' used Edward Bernays' propaganda. Similarly, popular opinion for the bellamy salute, changed around this time, which is why schools now use the hand-on-heart techqnique to instill the values. But that is getting off topic on an already off topic thread. The terms, community, developer relations, and technical evangelism, are all used to describe roles for corporate propaganda. The community, where propaganda is disseminated, exists more recently as corporate-sponsored technical events and, starting a few years back, on w3c mailing lists. Large numbers of individuals are organized (By Google, Microsoft, etc) to accept what is fed to them through these corporate vehicles, and willingly do so for three reasons (1) the great potential for career advancement via social climbing, (2) the large amount of money in corporate community, and (3) a shortage of corporate-free spaces. The term community has long been coopted outside the world of tech, generally to leverage herd mentality, so as to control, categorize, marginalize, and otherwise take advantage of subsets the public. And so now too in software, where companies hire representatives to promote agendas, the community represents something of value to them: influence. Developer relations and community managers are generally presentable, attractive, and serve their company's agenda. Programming skill is not so important. Appearance and presentation are. Developer relations is generally very well-compensated for very light work hours (e.g. $150k+ 4d/wk, 6h/d). Don't get me wrong, I'm all for working fewer hours! -- my point is that community, and those who manage to shape it, play a significant role in the corporate agenda to the expense of anything resembling consensus-based voluntaryist community. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: The initialization steps for Web browsers
On 6/10/14, Ian Hickson i...@hixie.ch wrote: On Tue, 10 Jun 2014, Allen Wirfs-Brock wrote: Hi Ian; Allen. (Also, how could step 6's substeps ever get triggered?) Working backwards, step 5 does many things, some of which are specified as having error conditions and exceptions, so I have to take into account what happens if any errors occur. Step 6, just says that if they do then the startup of the ES environment has failed. If an implementor can prove that they [can't] trigger any of those error conditions then they don't have to worry about it. But for completeness, I do. Do you have an example of how any of those steps could fail? I'm guessing that applies for any early error. script var tew; continue; // early error; `tew` is not bound. /script script alert(rrq); var rrq; g; // ReferenceError, not an early error; `rrq` is bound. /script The following example results in a ReferenceError. Although `gv` is defined, that does not occur until the subsequent script. After the browser has reached the first /script, the Program is evaluated, and at that point, the global Lexical Environment Record does not have a `gv` property. Where and how is this behavior described? scriptalert(gv); // context to subsequent script is segmented. /script scriptvar gv;/script I vaguely remember seeing examples more complex than the example above, including dealings with the global scope polluter, and with more divergent behavior. Moving `gv` to the same script results results in no such runtime error, as is explained in ES3. script alert(gv); // contiguous context in same script. var gv; /script -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Date Object Doesn't Work.
On 5/28/14, Andrea Giammarchi andrea.giammar...@gmail.com wrote: Hi Andrea - While I agree we should expect consistent results, you might get more consistent one via UTC time, i.e. ``` var r = new Date(2013, 02, 10), r2 = new Date(2013, 02, 10), diff = 7; r.setUTCHours(2 + diff); r2.setUTCHours(3 + diff); ``` Above operation will actually show 1 hour difference in all browsers (visually 2 due -8 VS -7 zone) The difference between 2am and 3am on that date, for this timezone (America/Los_Angeles), is zero. diff isn't needed to calculate DST-free difference. r Sun Mar 10 2013 01:00:00 GMT-0800 (PST) Given arbitrary dates and timezones, tzo difference might or might not cross DST and that might be adjusted by the user. But calculating DST-free difference seems like a safer bet. And so the way to do that would be to send a local date but treat it as UTC. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Date Object Doesn't Work.
Yesterday, I posed the question about an event starts at 2am, 2014, and ends immediately after 3 am, on May 9, how long is it? The event, in that case, should be 23 hours due to 1h DST loss. (spring forward). But then I noticed more anomalies: !doctype html head titletest DST 1/title style head, script { display: block; white-space: pre; font-family: monospace; } /style script var d = new Date(2013, 02, 10), d2 = new Date(2013, 02, 10); d.setHours(1); d2.setHours(2); function showResult() { document.getElementById(out). firstChild.data = d: + d.toString() + \nd2: + d2.toString() + \nd2 - d: + (d2 - d) } window.onload = showResult; /script /head h2result/h2 pre id='out'-/pre /body /html Chrome, Opera: d: Sun Mar 10 2013 01:00:00 GMT-0800 (PST) d2: Sun Mar 10 2013 01:00:00 GMT-0800 (PST) d2 - d: 0 Safari: d: Sun Mar 10 2013 01:00:00 GMT-0800 (PST) d2: Sun Mar 10 2013 03:00:00 GMT-0700 (PDT) d2 - d: 360 Firefox: d: Sun Mar 10 2013 01:00:00 GMT-0800 (PDT) d2: Sun Mar 10 2013 03:00:00 GMT-0700 (PDT) d2 - d: 360 What are Opera and Chrome doing? Here in CA, we recognize DST, and so 0 would be wrong, as 2am gets set forward to 3am but the offset changes, too. I believe Safari is correct here. Now from 2am - 3am, the difference should be 0 because 2am gets set forward to 3am. !doctype html head titletest DST 2/title style head, script { display: block; white-space: pre; font-family: monospace; } /style script var r = new Date(2013, 02, 10), r2 = new Date(2013, 02, 10); r.setHours(2); r2.setHours(3); function showResult() { document.getElementById(out). firstChild.data = r: + r.toString() + \nr2: + r2.toString() + \nr2 - d: + (r2 - r) } window.onload = showResult; /script /head h2result/h2 pre id='out'-/pre /body /html Firefox: r: Sun Mar 10 2013 03:00:00 GMT-0700 (PDT) r2: Sun Mar 10 2013 03:00:00 GMT-0700 (PDT) r2 - d: 0 Safari: r: Sun Mar 10 2013 03:00:00 GMT-0700 (PDT) r2: Sun Mar 10 2013 04:00:00 GMT-0700 (PDT) r2 - d: 360 Opera, Chrome: r: Sun Mar 10 2013 01:00:00 GMT-0800 (PST) r2: Sun Mar 10 2013 03:00:00 GMT-0700 (PDT) r2 - d: 360 Firefox seems to get this right, forwarding 2am to 3am. What is going on with the others? -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [whatwg] Date Update?
On 5/25/14, Norbert Lindenberg ecmascr...@lindenbergsoftware.com wrote: On May 19, 2014, at 11:34 , Garrett Smith dhtmlkitc...@gmail.com wrote: On 1/19/14, Norbert Lindenberg ecmascr...@lindenbergsoftware.com wrote: On Jan 19, 2014, at 10:01 , Jasper St. Pierre jstpie...@mecheye.net wrote: On Sunday, January 19, 2014, Garrett Smith dhtmlkitc...@gmail.com wrote: [...] I should have clarified my assumption that we're talking about locale sensitive parsing, since your case below appears to be about locale independent parsing. Locale-sensitive for event view/CrUD by users in multiple timezones. Case: Server sends back JSON that is used to build a calendar component or Gantt chart The application parses the start and end of the times given over the JSON (and I have some JSON in the application that I am developing right now; see below). Since the start and end times are parsed by the application (and not directly presented to the user), they should be represented in a locale independent form. If they're just points in time, you can use either a JSON number representing the time value of a Date object, or a JSON string in ECMAScript Date Time String Format with Z. If not, please clarify your requirements. The start and end dates are shown in the UI. Locale-sensitive display is needed for CrUD with multiple timezones and users in multiple timezones. Given a logged-in user with an application-stored timezone: Backend (BE) stores events in UTC. Event dates are transmitted as an ISO string, local to that event, to the user. 5pm CA -- 12am UTC 12am UTC -- 8am China We're in DST here. Even when the CA user is travelling to Hawaii, the event starting from 5pm in CA time is displayed in the app as 5pm, and not 8pm (which will be shown on his system clock at that moment). Question: If the even starts at 2am and ends immediately after 3 am, on May 9, how long is it? I want something like: zonedDate.setTimezoneOffset(America/New_York) This would allow the user to change start and end times and the duration would be correct. exactly according to the dates and times specified. For example, if the event starts on 2014-01-01 2014-01-11, to match the 10/31 below? No, the element is positioned ten thirty-firsts of the way through that month; the month is an LI element, and yes; that's background info. Operating systems already have ways to let the user select their time zones, Hopefully they're not so limited as the UI they display. Macs to miss a lot of cases. E.g. Navajo Nation. (Probably it should be named Macbook Amateur. [3] http://norbertlindenberg.com/ecmascript/intl.html#sec-12.3.3 | The function returns a new object whose properties | and attributes are set as if constructed by an object | literal assigning to each of the following properties the | value of the corresponding internal property of this | DateTimeFormat object (see 12.4): locale, calendar, | numberingSystem, timeZone, hour12, weekday, era, | year, month, day, hour, minute, second, and timeZoneName. | Properties whose corresponding internal properties are | not present are not assigned. Does it allow me to get a TZO or just the timezone back? dateObj.getTimezoneOffset(America/Shiprock) would fit what I need. You mixed lexical grammar (object literal), properties of an object, and behavior in a very confusing paragraph. I reread it a bunch of times but can't squint my brain quite right enough to grok it. hourNo0 seems like something to force midnight to be zero, but instead it mentions 11 vs 12. Other problems: Timezones cannot be referred to as static offsets. If that lets me set an IANA timezone and then add that to a calendar, and then calculate the correct tzo based on an ISO local date format. DST rules change and ES5 allows implementations to apply the changes proactively/retroactively. That's unreliable. ES5 ISO implementation is broken. IANA timezones account for leap seconds. ECMA forbids leap seconds. How do you intend to reconcile this? -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [whatwg] Date Update?
On 5/27/14, Garrett Smith dhtmlkitc...@gmail.com wrote: Question: If the even starts at 2am and ends immediately after 3 am, on May 9, how long is it? Correction: Mar 9, not May 9. -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Integrating the Webs' dependency systems
On 5/23/14, Ian Hickson i...@hixie.ch wrote: On Fri, 23 May 2014, Ryosuke Niwa wrote: On May 23, 2014, at 3:14 PM, Ian Hickson i...@hixie.ch wrote: Hi guys - - script needs= in HTML Could someone give me a pointer about this? This is the first time I've heard of this feature. It's a work in progress, but the last public post from me about it was: http://lists.w3.org/Archives/Public/public-whatwg-archive/2013Aug/0277.html CoR meets browser resources. That looks familiar! Especially Use-case U. See: defer on style, depends. http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-February/018439.html The examples that appear linked to my prior site at dhtmlkitchen.com are not available anymore, unfortunately. That was when I was using Java, before it fell out of style. And incidentally, the CoR pattern proposal was inspired by Apache Ant. (credit where credit is due). And can we change needs= back to depends=? The basic theme of script needs= is making it possible for resources (probably more than just scripts) depend on each other and delay loads until they are needed. For example, being able to say this script shouldn't download yet. Shouldn't download or shouldn't be evaluated? When it is needed, though, it should also download and apply this style sheet, Stylesheets, too? :-) -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
FunctionDeclaration as an element of a Block statement's StatementList
Prior to the Sixth Edition, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement's StatementList. The problem is not necessarily that FunctionDeclaration appears in a Block, that FunctionDeclatation appears in places in a program where a Statement is permitted but a FunctionDeclaration is not. ES5 mentioned it: Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. I don't have a concrete proposal, but I wonder why specifying as ES6 does makes less sense to take the text that ES5 had in s 12 and attempt to codify, as ES6 does, except using Statement instead of StatementList. http://ecma-international.org/ecma-262/5.1/#sec-12 https://people.mozilla.org/~jorendorff/es6-draft.html#sec-web-legacy-compatibility-for-block-level-function-declarations -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Error Instances Stack Property
Should Error Instance have a standard `stack` property? Seems to be a very common feature nowadays. Why isn't it being specified in EcmaScript 6? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack Thanks, -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [whatwg] Date Update?
On 1/19/14, Norbert Lindenberg ecmascr...@lindenbergsoftware.com wrote: On Jan 19, 2014, at 10:01 , Jasper St. Pierre jstpie...@mecheye.net wrote: On Sunday, January 19, 2014, Garrett Smith dhtmlkitc...@gmail.com wrote: What considerations are there for codifying the behavior for Date.parse? Middle endian date format parsing works: Date.parse(2/11/2013); Should this be standardized here: http://javascript.spec.whatwg.org/#date Any proposals for Date.prototype.format, ala strftime? The ECMAScript Internationalization API provides date and time formatting, with an API that's more abstract and better suited to localization than strftime: http://www.ecma-international.org/ecma-402/1.0/#sec-12 http://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html#DateTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat Parsing date and time input was considered for the second edition of that standard, but our impression was that most applications prefer date-and-time pickers, so we dropped parsing. I was talking about formatting, not parsing. But now you're talking about formatting, and can't help but strongly disagree with what you've written. Case: Server sends back JSON that is used to build a calendar component or Gantt chart The application parses the start and end of the times given over the JSON (and I have some JSON in the application that I am developing right now; see below). After the JSON is parsed, UI components, what I've dubbed timeline events get created and added to the requisite year (created and added, filling in any elided years as necessary). (The year calendar element happens to be a UL with LI for each month). After the correct year element(s) are created, the timelineEvent can be added. Each timeline event has a startDate, an endDate, and a duration. The startDate is used to create and then to append the timelineEvent element to month of the year in which it appears, where its position is adjusted so that its position and placement appears exactly according to the dates and times specified. For example, if the event starts on 2014-01-01 and ends on 2014-03-01, then the element is positioned 10/31 of the way into january and at the beginning of March. Any replacement proposals, like a Joda-Time, or others, that treat a Date as a set of fields rather than an object represented by a number? And maybe with add/subtract methods without having to resort to each field? Zero-based month and one-based days are weird, but even weirder with MakeDay adding the extra month onto the year field: var d = new Date(Date.now()) d.setMonth(12); // Next January, not December. Date is a wrapper for a UNIX timestamp. It's not designed to be an accurate calendaring API. I feel like a calendering API should be related to Date and integrate with it, but a separate API altogether. Computer representations of date and time are complicated enough, and should we want a standard calendering API, it should be done by not wrapping a UNIX timestamp. Joda-Time doesn't treat Date as a set of fields; it uses a complete separate DateTime class. Treating Date as a set of fields, as the current Date API attempts, is inadequate because it doesn't allow for different calendars (Gregorian, Buddhist, Islamic, etc) and time zones. The getters and setters for fields in java.util.Date, for comparison, have all been deprecated. LocalDate object sounds really useful. How would that best be done? What is a good way determine a physical location and map that to a timezone, and have the timezone be associated with that date? http://lists.w3.org/Archives/Public/public-script-coord/2014AprJun/0051.html That said, there hasn't been much interest in adding anything of the size of Joda-Time into ECMAScript. I proposed a while ago to make public the one-way mapping from Date values to date and time fields that's already specified in the Internationalization API spec, but even that hasn't gotten much traction yet: https://bugs.ecmascript.org/show_bug.cgi?id=698 Sure, but the ECMAScript 5 got ISO-8601 wrong by stating: | The value of an absent time zone offset is Z http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 ECMAScript draft 6 corrects this mistake: | If the time zone offset is absent, the date-time is interpreted as a local time. https://people.mozilla.org/~jorendorff/es6-draft.html#sec-date-time-string-format -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [whatwg] Date Update?
On 5/19/14, Garrett Smith dhtmlkitc...@gmail.com wrote: On 1/19/14, Norbert Lindenberg ecmascr...@lindenbergsoftware.com wrote: On Jan 19, 2014, at 10:01 , Jasper St. Pierre jstpie...@mecheye.net wrote: On Sunday, January 19, 2014, Garrett Smith dhtmlkitc...@gmail.com wrote: What considerations are there for codifying the behavior for Date.parse? Middle endian date format parsing works: Date.parse(2/11/2013); Should this be standardized here: http://javascript.spec.whatwg.org/#date Any proposals for Date.prototype.format, ala strftime? The ECMAScript Internationalization API provides date and time formatting, with an API that's more abstract and better suited to localization than strftime: http://www.ecma-international.org/ecma-402/1.0/#sec-12 http://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html#DateTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat Parsing date and time input was considered for the second edition of that standard, but our impression was that most applications prefer date-and-time pickers, so we dropped parsing. I was talking about formatting, not parsing. But now you're talking about formatting, (I meant to say that you're talking about parsing). -- Garrett @xkit ChordCycles.com garretts.github.io ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Function Syntax
On 5/10/11, Allen Wirfs-Brock al...@wirfs-brock.com wrote: On May 10, 2011, at 4:53 PM, Douglas Crockford wrote: I look at ECMAScript as serving four groups: 1. The beginners for whom the language was designed. 2. The web developers who owe their livelihoods to the language. Library users. 3. The scientists who will use the language for greatness. Not much greatness in web development these days, is there? 4. Language designers and critics. I'm fine with calling these traits; calling them mutually exclusive categories is a thinking error. I'm not exactly sure what you mean by scientists. The third group I would identify are professional software developers who will use the language to implemented complex applications of the soft that today are more commonly implemented using Java, C++, etc. These are larger systems that need more emphasis upon upon abstraction building in order to manage the domain and application complexity. At a meeting today, the dichotomy we used in talking about this is the difference between imperative programmers and abstraction builders. Imperative programmer know how to use basic imperative statements to manipulate predefined abstractions. Abstraction builders create such abstractions. I think that all of your #1 and much of #2 are imperative programmers. While we need to continue to improve the language for this group we also need to start better serving the needs of the abstraction builders. Much of what we have promoted to proposal status seems to be oriented target on this latter group. The mentality that imperative programmers and abstraction builders are non-overlapping is a thinking error that pissed me off to the end of my career as a javascript programmer. Abstractions aren't to be done by the ivory tower architect (or js library author or javascript guru). They're created out of need. The need comes from fulfilling the requirements. I recommend Domain Driven Design, by Eric Evans (and I have a copy for sale, in excellent condition). Please don't design Ecmascript based on categorizational false dichotomies. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: arrow syntax unnecessary and the idea that function is too long
On 5/10/11, Oliver Hunt oli...@apple.com wrote: [...] I think I'd prefer the #{ expr } or #(args...){ expr } syntaxes simply to\ What good is Arguments? [...] * Generalised object subtyping * Probably Mark's simple map and set APIs -- these can be implemented in\ If it's wish list time, then I'll say triple quotes: div.innerHTML = span id=foo class='bar'#str/span ; (if not, then I apologize fro being off topic). -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: arrow syntax unnecessary and the idea that function is too long
On 5/7/11, Faisal Vali fais...@gmail.com wrote: Kyle Simpson get...@gmail.com Date: Sat, 7 May 2011 21:58:32 -0500 Subject: Re: arrow syntax unnecessary and the idea that function is too long snip With all due respect, Brendan's personal tastes on what kind of code he likes to write is not enough. It has to be something that is likely to find wide spread support among the JavaScript masses. Since the arrow syntax assailants have been quite vocal on this list, Yeah, not much vocal whatevers, right? I haven't seen much into the benefit of -. I haven't given it a whole lot of thought and don't find it all that thrilling, really. Unusually underopinionated for me, I know. Though If I was forced to pick between - and #, I'd pick #. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: arrow syntax unnecessary and the idea that function is too long
On 5/7/11, Isaac Schlueter i...@izs.me wrote: [...] Blocks in JS are useless, can't we just do away with them? Blocks are required for many productions such as try/catch/finally. Almost all existing code uses blocks to group statements together. Blocks can't be removed. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Best practices for exception handling?
On 4/29/11, Dmitry A. Soshnikov dmitry.soshni...@gmail.com wrote: On 30.04.2011 0:22, Axel Rauschmayer wrote: With JavaScript, is throwing a string considered bad style (now or in the future)? That is, is throwing a new Error(msg) better than throwing msg directly? Why? To get a meaningful `error.stack` ? ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/19/11, Brendan Eich bren...@mozilla.com wrote: On Apr 19, 2011, at 8:39 AM, Isaac Schlueter wrote: This style is more easily scanned. The important tokens are along the left edge, which forms a straight line with logical and orderly breaks, and those tokens are not overused, so their presence or absence is very noticeable. The right-edge is jagged, and when every line has a ;, the brain tends to filter out their presence, making it hard to notice their absence. This is accurate in my experience. Even experienced semicolon users sometimes leave a few out, and the lack is hard to see. Restricted productions are the most benign cases. How ASI changes program behavior WRT unrestricted productions is bigger problem. Can you provide examples of the sort of unrestricted productions you're referring to, where unexpected semicolon insertion changes program behavior? In my experience, it is the *lack* of ASI that usually causes problems with unrestricted productions. Must be what Garrett means, since ASI is *only* error correction, plus of course built-into-the-grammar restricted productions. So ASI does *not* change program behavior from non-error behavior A to non-error behavior B. It instead suppresses early SyntaxError with successful evaluation, in a deterministic way. I don't mean to annoy by repeating the same things, but here goes: Is `()` Grouping Operator or Arguments? Is `[]` ArrayLiteral or Property Accessor? Or do these cases depend on the preceding token? I'll take your prose on with an example Non error B behavior, b.js: (function() { /*...*/ }); Non-error A behavior, a.js: var MyWidget = function(){ this.name = mike; } Now concatenate a.js and b.js and you have: var MyWidget = function(){ this.name = mike; }(function() {}); Which makes MyWidget undefined and sets window.name to mike. That's all fine if you you notice it right away. But what if `MyWidget` gets called in a callback of some sorts, and that callback never fires? Well, sure, you might say that would be a lazy developer and faulty QA, but IMO it would be much nicer to be fail fast. That example, BTW, is in http://jibbering.com/faq/notes/code-guidelines/asi.html as is the example with array literal/square bracket property accessor. https://mail.mozilla.org/htdig/es-discuss/2010-July/011600.html So any statement of the form ... ASI changes program behavior WRT unrestricted productions is bigger problem is simply misstated. See above. Again, it is the expectation of newline significance where none exists, where no error is corrected by ASI, that leads people astray. This is worth working to fix, or mitigate, provided migration works well. I don't understand what you mean. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/19/11, Isaac Schlueter i...@izs.me wrote: On Tue, Apr 19, 2011 at 11:02, Garrett Smith dhtmlkitc...@gmail.com wrote: On 4/19/11, Brendan Eich bren...@mozilla.com wrote: I don't mean to annoy by repeating the same things, but here goes: Is `()` Grouping Operator or Arguments? Is `[]` ArrayLiteral or Property Accessor? Or do these cases depend on the preceding token? They depend on the preceding token, *and* they cause a preceding \n to be elided. That is the problem with JavaScript's statement termination rules with respect to lines that start with +, /, *, -, (, or [. Now concatenate a.js and b.js and you have: var MyWidget = function(){ this.name = mike; }(function() {}); That error isn't caused by ASI. Disabling ASI won't prevent that error. That error is caused by the lack of ASI. It's caused by the \n being elided when the next line starts with a (. So any statement of the form ... ASI changes program behavior WRT unrestricted productions is bigger problem is simply misstated. See above. ASI didn't change the program behavior. ASI didn't happen in that example. Newline elision changed the program behavior. No, `MyWidget = function(){}` was not explicitly terminated by a semicolon. The end of the input stream is reached and a semicolon is inserted. Newline elision did not change behavior. Concatenation of a.js and b.js results in behavior that is not the same as when a.js and b.js are in separate files. In a.js, there was a missing semicolon after the FunctionExpression. On its own, a.js does what was wanted of it. File b.js contains what the author wanted as a grouping operator and it works fine as b.js alone. But concatenating a.js + b.js to one file, the result is different behavior. That's a problem. The changed behavior problem is avoidable, by beginning files with `;` (as already mentioned in this thread). Dojo.js does that, for example, to avoid the problem of changed behavior when runing through shrinksafe or yuicompressor (both of which concatenate and minify) thus avoiding the potential for different program behavior. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/19/11, Brendan Eich bren...@mozilla.com wrote: On Apr 19, 2011, at 3:08 PM, Garrett Smith wrote: On 4/19/11, Isaac Schlueter i...@izs.me wrote: ASI didn't change the program behavior. ASI didn't happen in that example. Isaac is correct. Newline elision changed the program behavior. Or newlines being insignificant whitespace, let's say. I don't see how whitespace is relevant here. No, `MyWidget = function(){}` was not explicitly terminated by a semicolon. The end of the input stream is reached and a semicolon is inserted. Not in the concatenation of a.js and b.js. Please attend to your own example. No, when a.js exists on its own, a semicolon is inserted. When concatenated with b.js that doesn't happen. Only if a.js is processed as a Program (the grammar's goal nonterminal), in which case, yes, ASI kicks in, and no, there is no subsequent ( or [ or similar input to cause trouble. That's what I'm talking about. Newline elision did not change behavior. Concatenation of a.js and b.js results in behavior that is not the same as when a.js and b.js are in separate files. That is true, but now you are changing the terms of the debate. The claim that ASI does not affect non-error semantics applies for any given Program -- not for Program X and Program Y. Is it program or Program we're discussing? What'd I write? If I wrote Program I take it back. But if I wrote program then I got what I meant write (and pedantic misquoting is a waste of time). What you describe is a hazard, we've covered it. But your argument foundered on ASI applying differently on two different programs. Of course that can happen. If ASI is warned by the interpreted, then the developer of a.js will know before running through compression tools. If that ASI were to be an error, then it would be fail fast. Call me a hater if it makes you feel better, but I find fail fast to be a lot better. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/19/11, Garrett Smith dhtmlkitc...@gmail.com wrote: On 4/19/11, Brendan Eich bren...@mozilla.com wrote: On Apr 19, 2011, at 3:08 PM, Garrett Smith wrote: On 4/19/11, Isaac Schlueter i...@izs.me wrote: ASI didn't change the program behavior. ASI didn't happen in that example. Isaac is correct. Newline elision changed the program behavior. Oh, yep. I wrote program. Tsk. [...][ Is it program or Program we're discussing? What'd I write? If I wrote Program I take it back. But if I wrote program then I got what I meant write (and pedantic misquoting is a waste of time). Right, not write. Now that's ironic. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/19/11, Brendan Eich bren...@mozilla.com wrote: [...] But good point. Indeed, feel free to file a bug at https://bugzilla.mozilla.org asking for such a warning. I'll support it. I'll do it. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/19/11, Brendan Eich bren...@mozilla.com wrote: [...] You are asking for an warning when a file ends without a semicolon required by the grammar, and ASI kicks in. Fair point, good idea. It's not going to do enough by itself, since warnings are easy to miss, and often annoy the wrong party (the user of content, where the dev is long gone). A good start. But good point. Indeed, feel free to file a bug at https://bugzilla.mozilla.org asking for such a warning. I'll support it. https://bugzilla.mozilla.org/show_bug.cgi?id=651346 -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictabilityandcontrol; alternatives
On 4/18/11, Claus Reinke claus.rei...@talk21.com wrote: The only places where semicolons are ever used in the Node.js package manager are in the 'for' loops headers and at the *beginning* of the lines that would be interpreted incorrectly because of the lack of the semicolon at the end of the *previous* line - for example see: https://github.com/isaacs/npm/blob/master/lib/utils/read-json.js#L320-L336 There are no semicolons at the end of lines *at all*. Also the commas in multi-line arrays and parameter lists are always written at the *beginning* of lines so Node also depends on the ASI *not* inserting semicolons if the next line starts with a comma or other operator. Thanks. It is useful to have such concrete examples. If you can think it, there is a porn for it. ]...] [aside: it would be nice to know who the committee members are, and what the process is for starting an official proposal] Who are the committee members? For the specific case of ASI, Brendan has explained the issues https://mail.mozilla.org/pipermail/es-discuss/2011-April/013794.html Restricted productions are the most benign cases. How ASI changes program behavior WRT unrestricted productions is bigger problem. In brief, there is no way simply to take away ASI, and any attempt to introduce a less troublesome variant of ASI will have to offer a way to deal with existing code. The number of developers advocating ASI as a best practice can't be stopped either. 'legacy' code here refers not to ancient, badly written code but simply to code using the current ASI, which is a legacy from the point of view of any revised ASI. Right. ASI reform would not have the intention to force coders to add semicolons everywhere, it would merely try to make the rules of syntax easier to understand for coders and less troublesome for language designers. The goal would be to avoid unnecessary syntax while also avoiding unnecessary worrying about how the mechanism works. As a coder, you really don't want to add semicolons to avoid ASI traps, as in line 232 of your example ;[dependencies, devDependencies].forEach(function (d) { Exactly. Because otherwise, that array might be property accessor. Why do I want to have to worry about what might have been omitted? No, I want to worry about what the code says. I consider a statement terminator to be just that; when I read it, I see end of statement. don't want to read beginning of statement preceeded by empty statement. As a language designer, there are more than enough issues to resolve, without having to watch your back wondering how ASI will interact with new grammar. Exactly. Multiline comments add extra problems. Hope that clears up things a little? Totally agree with you on this one. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictability and control; alternatives
On 4/17/11, Brendan Eich bren...@mozilla.com wrote: On Apr 17, 2011, at 10:52 AM, Claus Reinke wrote: [TLDR] ASI is not going to be removed. I don't know why you think it could be. Why not? Iif developers would stop doing that then eventually, can't it be removed? It is not hard at all to write code that does not rely on ASI. Existing code that relies on ASI would fail, so making ASI an error today would not be feasible because many sites would break. It might sound naive, but can ASI be phased-out? How can we get developers to stop using ASI? Can ASI be made to be an error for strict mode? IIRC Asen proposed that a couple of years ago. What if ASI were to trigger a warning to developers? ES5 does not define warning. By warning, I mean an error condition that is reported by the implementation but does not trigger abrupt completion (Deprecated production: missing semicolon, line 29). The warning may be hidden but activated in a debugging environment (as optionally provided by the implementation). -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictability andcontrol; alternatives
On 4/17/11, Mike Ratcliffe mratcli...@mozilla.com wrote: I remember going over a few hundred thousand lines of JavaScript and adding semicolons because I had decided to minify it. I also remember that for months I was receiving bug reports from sections of code where I had missed the semicolons. Now I am obsessed with adding semicolons everywhere that they should go. ASI changes program behavior. Worthy (IMBO) reads on Jim's fickle server: http://jibbering.com/faq/notes/code-guidelines/#asi http://jibbering.com/faq/notes/code-guidelines/asi.html There are plenty of beginners who haven't experienced those problems (see SO for details). Personally I would welcome some kind of option to disable ASI with open arms. Garrett's strict mode warning idea makes sense to me but I am fairly certain that not everybody would welcome it. IIRC, it was Asen who first proposed that idea. COuldn't find the actual post, but: http://dmitrysoshnikov.com/ecmascript/the-quiz/#comment-8 It would also take some evangelism to explain to beginners who don't see the problems. Again, see stackoverflow. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictability andcontrol; alternatives
On 4/17/11, Allen Wirfs-Brock al...@wirfs-brock.com wrote: On Apr 17, 2011, at 12:33 PM, Mike Ratcliffe wrote: ... Personally I would welcome some kind of option to disable ASI with open arms. Garrett's strict mode warning idea makes sense to me but I am fairly certain that not everybody would welcome it. ~ I'd suggest that this isn't really a standards issue. The standard does not prevent an implementation from providing whatever sort of supplemental diagnostic output it deems appropriate. You could even issue warnings recommending another programming language if you wanted. It also doesn't block an implementation from providing a user selected mode that excludes certain standard features such as ASI, it just means that when operating in that mode the implementation isn't conforming to the standard. To be compatible with the standard and the web, an ECMAScript implementation is still going to have to default to accepting code that depends upon ASI. However, the implementation can gripe about it all it wants on a diagnostic channel. Which major browser implementations discouraging developers from using ASI and how effective is it? Implementations are motivated to get scripts working and conform to specs. How could Ecma encourage developers to stop using ASI? I initially thought that standard warnings in strict mode would help. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictability and control; alternatives
On 4/17/11, Jason Orendorff jason.orendo...@gmail.com wrote: On Sun, Apr 17, 2011 at 12:07 PM, Garrett Smith dhtmlkitc...@gmail.com wrote: On 4/17/11, Brendan Eich bren...@mozilla.com wrote: On Apr 17, 2011, at 10:52 AM, Claus Reinke wrote: [TLDR] ASI is not going to be removed. I don't know why you think it could be. Why not? Iif developers would stop doing that then eventually, can't it be removed? We have a saying at Mozilla: Don't break the web. If a browser vendor removed ASI support from their ES engine, many existing sites would stop working. Their users would switch to other browsers. I wrote eventually. As naive as it may seem, it is conceivable that newly written scripts could be authored so that they don't rely on ASI (yeah right, you say). And if that happened then the number of scripts that rely on ASI would diminish in number. ASI is often unintentional. If I do that (and I have) I definitely wnat to know right away; not after I deploy my app. Intell-J warns for this in the js editor. A standard warning for ASI would be helpful in this way. I know it sounds fantastical, but before saying impossible, think about this: What effectively discourage authors from using ASI (intentionally or otherwise)? ES5 does not define warning. By warning, I mean an error condition that is reported by the implementation but does not trigger abrupt completion (Deprecated production: missing semicolon, line 29) Most ES runs in browsers. If a browser shows a warning, it shows it to the end user of a web site--the wrong person. Why must the browser show the message to the end user? I didn't suggest that, so why are you? The implementation (script engine) can emit warnings (for Firebug, MSIE debugger, etc). My idea for standard warnings comes from my contempt for things like this: It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. which mentions warnings but the spec doesn't say what a warning really is. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictability and control; alternatives
On 4/17/11, Mikeal Rogers mikeal.rog...@gmail.com wrote: do modern javascript implementations actually insert semicolons? Function.prototype.toString says yes. ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Automatic Semicolon Insertion: value vs cost; predictability and control; alternatives
On 4/17/11, Wes Garland w...@page.ca wrote: On 17 April 2011 20:09, Garrett Smith dhtmlkitc...@gmail.com wrote: Function.prototype.toString says yes. That's not a really valid evaluation IMO. At least in mozilla's case, the semi colon appears in this by virtue of the bytecode decompiler putting a semicolon at the end of every statement. The source-code-as-compiled is not actually stored anywhere. OK, thanks for pointing it out. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Existential operator
On 4/14/11, Brendan Eich bren...@mozilla.com wrote: There is no ambiguity problem with ? followed by . and then (with whitespace allowed, of course) an IdentifierName. We need the lookahead to an identifier-name starting-character to avoid this: var tolerance = big ?.1:.01; So we can't simply maximum-munch '?.'. What about square-bracket property accessors? Is [propertyName] an Array or is it the new conditional property access with square-brackets? var p = o.v ? [propertyName]; -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Existential operator
On 4/13/11, Kyle Simpson get...@gmail.com wrote: See http://wiki.ecmascript.org/doku.php?id=strawman:default_operator -- the proposal there is ?? and ??= since single ? is ambiguous after an expression due to conditional expressions (?:). The default operator doesn't address a significant part of what Dmitry is asking for -- the . in the ?. usage -- which allows the property access to be expressed only once and used for both the test and assignment. I have sometimes wanted something like that to avoid temporary variables. The other (more awkward/obscure looking) way to do this is: var a; b a = c; a = b c; Your suggestion to change the ternary operator is interesting but creates incompatibility. It is not feasible. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: 'this' is more complicated than I thought (PropertyReferences break equivalences)
On 4/11/11, Claus Reinke claus.rei...@talk21.com wrote: Like most Javascript programmers, I have tended to follow a simple rule for functions using 'this': eta-expand method selections, use .bind, or get into trouble. That is unnecessary and inefficient. Instead, I use the following algorithm: For instance methods, always call with the base object or with call/apply. Don't use `this` in methods that are to be called as static, so you can use variable shortcuts for those static methods, pass them around. // DONT DO THIS var StyleUtils = { HAS_COMPUTED_STYLE : (function() { /*...*/ return true; })(), getStyle : function(el, name) { // FAILED STRATEGY, `this` in static context. if(this.HAS_COMPUTED_STYLE) { return worked; } return didn't work; } }; That most JavaScript programmers like to bind every function says more about trends in JavaScript programming than about JavaScript. Then I got curious about how method calls determine what object to pass as 'this': a method is a function selected from an object, and functions are first-class values, so, by the time they get called, how do we know where they came from? The base object. var o = { m : function(){ alert( this == o ); } }; o.m(); // true, o is base object var f = o.m; f(); // false. Calling f() results false because the base object is a declarative environment record (called VariableObject in ES3). And when that happens, the `this` value is either global object or null in ES5 in some cases. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: 'this' is more complicated than I thought (PropertyReferences break equivalences)
On 4/11/11, Claus Reinke claus.rei...@talk21.com wrote: Like most Javascript programmers, I have tended to follow a simple rule for functions using 'this': eta-expand method selections, use .bind, or get into trouble. That is unnecessary, inefficient, and adds clutter. That most JavaScript programmers do that says more about trends in JavaScript programming than it does about the language. Then I got curious about how method calls determine what object to pass as 'this': a method is a function selected from an object, and functions are first-class values, so, by the time they get called, how do we know where they came from? The base object. Follow these two rules to greatly reduce `this` reference confusion. 1. For instance methods (such as prototype methods), either qualify the method call with the base object or use call/apply. For example, var x = new X; x.m(); // Qualified instance method // DONT DO THIS var m = x.m; m(); 2. For static methods, write them so that they never use `this`. For example, here is an example of static method `getStyle` that violates that rule and uses `this`: // DONT DO THIS var StyleUtils = { HAS_COMPUTED_STYLE : (function() { /*...*/})(), getStyle : function(el, name) { // Problem: Use of `this` in static method. if(this.HAS_COMPUTED_STYLE) { } } }; By never using `this` in static methods, it can be assured that they can be aliased with a variable and passed around, e.g. `var getStyle = StyleUtils.getStyle`. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Standardizing out-of-memory and stack-depth-exceeded errors?
On 3/22/11, Joshua Bell j...@lindenlab.com wrote: I was noodling with a (toy) compiler-to-JS for a (dead) language that supports error handlers for two boundary conditions - stack depth exceeded out of memory - and noticed that the relevant behavior in JS is not standard across browsers. Has there been any discussion around standardization of errors thrown when limits of the script execution environment are hit? (Searching the archives didn't yield hits, but my search-fu may be weak today.) From briefly testing the boxes on my desk: stack depth: function a() { return a() + 1; } a(); * IE9: Error, message: 'Out of stack space' * Firefox 4: InternalError, message: 'too much recursion' javascript: alert(new InternalError(Got on tha inside, bitch!)); Hrm. seems odd to expose the constructor publicly. But FWIW, `new InternalError instanceof Error` is true. * Safari 5: RangeError, message 'Maximum call stack size exceeded' * Chrome 10: RangeError, message: 'Maximum call stack size exceeded', type: 'stack_overflow' Agree with Brendan. Seems strange. The infinite recursion could be detected and reported early. Where does that happen? Does any engine report early for infinite recursion? -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Standardizing out-of-memory and stack-depth-exceeded errors?
On 3/23/11, Mike Shaver mike.sha...@gmail.com wrote: On Wed, Mar 23, 2011 at 6:21 PM, Garrett Smith dhtmlkitc...@gmail.com wrote: javascript: alert(new InternalError(Got on tha inside, bitch!)); Hrm. seems odd to expose the constructor publicly. Necessary to permit instanceof testing, no? The infinite recursion could be detected and reported early. Where does that happen? Does any engine report early for infinite recursion? No; instanceof uses [[HasInstance]] which compares the Function's prototype property to the each objet in the object's prototype chain. If there is a match, the result is true. Otherwise, the result is false. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Standardizing out-of-memory and stack-depth-exceeded errors?
Bad quoting made it confusing, but I was (am) right. Edited as intended below: On 3/23/11, Garrett Smith dhtmlkitc...@gmail.com wrote: On 3/23/11, Mike Shaver mike.sha...@gmail.com wrote: On Wed, Mar 23, 2011 at 6:21 PM, Garrett Smith dhtmlkitc...@gmail.com wrote: javascript: alert(new InternalError(Got on tha inside, bitch!)); Hrm. seems odd to expose the constructor publicly. Necessary to permit instanceof testing, no? [...] No; instanceof uses [[HasInstance]] which compares the Function's prototype property to the each objet in the object's prototype chain. If there is a match, the result is true. Otherwise, the result is false. ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Standardizing out-of-memory and stack-depth-exceeded errors?
On 3/23/11, Mike Shaver mike.sha...@gmail.com wrote: On Wed, Mar 23, 2011 at 8:21 PM, Garrett Smith dhtmlkitc...@gmail.com wrote: Bad quoting made it confusing, but I was (am) right. Edited as intended below: On 3/23/11, Garrett Smith dhtmlkitc...@gmail.com wrote: On 3/23/11, Mike Shaver mike.sha...@gmail.com wrote: On Wed, Mar 23, 2011 at 6:21 PM, Garrett Smith dhtmlkitc...@gmail.com wrote: javascript: alert(new InternalError(Got on tha inside, bitch!)); Hrm. seems odd to expose the constructor publicly. Necessary to permit instanceof testing, no? [...] No; instanceof uses [[HasInstance]] which compares the Function's prototype property to the each objet in the object's prototype chain. If there is a match, the result is true. Otherwise, the result is false. I mean that you need the constructor exposed to test instanceof for InternalError. FOr what? -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Standardizing __proto__
On 3/18/11, Kyle Simpson get...@gmail.com wrote: There's LOTS of sites out there that still (unfortunately) do unsafe overwriting/overloading of the native's prototypes. For instance, just a few months ago, I ran across a site that was creating a Array.prototype.push() implementation that was incompatible with the standard implementation. When I injected jQuery onto that page, jQuery failed to work because Sizzle relies on being able to call push() with multiple parameters (something the page's .push() didn't handle). And there are many, many other examples, like adding String.prototype.trim(), etc. Yep. And JSON.parse, Function.prototype.apply, and others. Modifying built-ins' prototypes is a powerful feature and modifying __proto__ is even more powerful. The point? If everyone were in the habit of using sandboxable natives, like FuseBox provides, then that page could override it's version of Array all it wanted (even the native one), and my code, using Fuse.Array, would be perfectly safe. The example you mention creates a problem that can be avoided by instead using a feature test. It needs at least: if(!Array.prototype.push) { } Just doing that would avoid the problem, thus obviating the need for a workaround (with Sanboxes, etc). I'm not arguing that it is wrong to standardize __proto__, just that your example doesn't seem to support doing that. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: HTML5 spec. seems to unnecessarily ban strict mode event handlers
On 3/17/11, Juriy Zaytsev kan...@gmail.com wrote: Thanks for bringing this quirk to the surface. I remember being puzzled by the presence of this wording in HTML5 spec but never got a chance to do anything about it. By non-standard I meant not part of ECMA-262 standard (not that it's not part of any other standard, such as HTML5... which — to be precise — is not yet a standard, as far as I understand). I changed the wording of the test to make it clearer — http://kangax.github.com/es5-compat-table/strict-mode/ HTML5 is modular and granular. Each part can have a status. And while we're on this subject, I've been tinkering with compat. table of non-standard ES features across various (modern and not so modern) implementations — http://kangax.github.com/es5-compat-table/non-standard/ The table indicates FF as the only browser supporting Array generics. Array generics are standard and work in Webki, Opera and Chrome . I think you meant what I call static Array Generics, though I think I may have coined that term. That is, Array.push( a, f ); can be used in just Firefox. // Array Generic var a = {}; Array.prototype.push.call( a, f ); a[0]; // f // Static Array Generic var a = {}; Array.push( a, f ); a[0]; // f Some IE versions have bugs with using Array.prototype built-ins generically. For example, where `obj` is anything other than an Array, `Array.prototype.push.call( obj );` won't update `obj.length`. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: HTML5 spec. seems to unnecessarily ban strict mode event handlers
On 2/3/11, Allen Wirfs-Brock al...@wirfs-brock.com wrote: I was browsing Kangax's strict mode test result page (http://kangax.github.com/es5-compat-table/strict-mode/ ) and I noticed that he listed the recognition of a use strict directive of a event handler as a non-standard feature that he tests for. javascript: void(document.body.setAttribute(onclick, 'use strict;'\nalert(this);)); alert(document.body.onclick); To be sure, I checked the event handler section of the HTML5 spec (http://dev.w3.org/html5/spec/Overview.html#event-handler-attributes) and to my surprise I discovered that it specifies the creation of the handler function in a manner that, at first glance, seems to explicitly cause the presence of a use strict directive to be ignored. Essentially it seems to specify that event handlers specified using the event handler attribute are never executed in ECMAScript 5 strict mode. I don't know whether or not this was intentional, but it certainly seems wrong. The strictness of an ECMAScript function is an internal and local characteristic of the function. For a ECMAScript host to say that a use strict directive is ignored is really no different from saying that IfStatements or any other syntactically valid element of a FunctionBody will be ignored. The HTML5 spec. get into this trouble because of the way it uses the abstract operation for creating function objects defined by section 13.2 of the ES5 specification HTML 5 also specifies that the function's `call` callback is called when in fact that does not happen at all. http://dev.w3.org/html5/spec/Overview.html#event-handler-content-attributes When an event handler's Function object is invoked, its call() callback must be invoked with one argument, set to the Event object of the event in question. Instead, it should say something like when the event handler is invoked, the callback function is called. And to add to that D3E should say (and it has been agreed upon) that the `this` value (cntext) for callbacks oef event handlers is set to be the current target object. Sprruy, I have only scanned and skimmed cause I'm too damn lazy :-D. But would there be any problems with doing things like that, Allen? -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: HTML5 spec. seems to unnecessarily ban strict mode event handlers
On 2/3/11, Allen Wirfs-Brock al...@wirfs-brock.com wrote: Regarding the call language, it would probably be best if it was described in terms of invoking the [[Call]] internal method of the handler's function object. However, that might be unnecessary if if the WebIDL ECMASCript binding makes it clear that the effect of invoking the call method of the Function interface is defined in terms of [[Call]]. But browsers don't call the `call` property of the function object. It's easy to test that: Create a function and give it an own call property on a function or by replacing Function.prototype.call. function x() { alert(1); } x.call = function() { alert('call()'); }; We may have clashing spec. terminology here but I think the intent seems clear enough. Uh uh. ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: substitutes for arguments and arguments.callee in ECMAScript 5
On 1/5/11, Allen Wirfs-Brock al...@wirfs-brock.com wrote: [...] the function expression form has a well-defined meaning anywhere including in the compound statement blocks such as if-statements. The meaning of the latter two declaration forms are not defined by the standard when they occur within compound statement blocks. What they do, depends upon the browser. [...] ES5 note uses some terminology that I don't understand. disallow usage? issue a warning? What do those mean? It'd make sense to say throw a SyntaxError. What does it mean to issue a warning? When does it happen? After the misplaced FD early (as early errors)? Or do warnings cause for abrupt completion? I'd prefer An implementation that handles FD as a Statement must issue a warning but I think issue a warning should be defined. -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Private names use cases
On 12/20/10, Allen Wirfs-Brock al...@wirfs-brock.com wrote: I've seen mentions in the recent thread that the goal of the Private Names proposal was to support private fields for objects. While that may be a goal of some participants in the discussion, it is not what I would state as the goal. I have two specific use cases in mind for private names: 1) Allow JavaScript programmers, who choose to do so, to manage the direct accessibly of object properties. This may mean limiting access to methods of a particular instance, or to methods of the same class, or to various friends or cohorts, etc. If private is based on lexical scope then it's already possible but it can be a bad smell. For example: var Blah = function() { var privateBlah = { complicatedDirtyWork : function() { alert(blah.) } }; var Blah = { goBang : function() { privateBlah.complicatedDirtyWork(); } }; return Blah; }(); Blah.goBang() Great for a one-off, but when you wanna have many of the ADT (many instances of Blah), then there's an equal number of privateBlah and the strategy must make some sort of lookup, e.g. var delegateBlah = getPrivateBlah( this ); delegateBlah.doTrick(); That's a bit more work and when there are only a couple of fields, it seems like too much trouble. If it were authored in a way that obviates that cruft but could still be facilitated by using scope tricks, as above? -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Function declarations as statements
On 11/11/10, Michael Day mike...@yeslogic.com wrote: Hi Brendan and Allen, Thanks for the pointers. So for Harmony, we are reclaiming function in block (must be a direct child of a braced block) to bind a block-local name on block entry (so hoisting lives, but only to top of block -- so you can't emulate with var f = function ...). If we implemented this behaviour now, I think that would be sufficient to make JQuery Arrogant bunch of lackeys. and Raphaël work. Here is an example from JQuery that is giving us trouble: I am now reminded of the logo Allen proposed for ECMAScript. if (condition) { var val, props, ... ; function getWH() { ... this is the function ... } http://bugs.jquery.com/ticket/6788 I've told them about this sort of problem and they just delete the comments. | GarrettS commented on jquery/jquery August 26, 2010 | | The comment has since been removed. | | GarrettS commented on jquery/jquery August 26, 2010 | | The comment has since been removed. More reasons why I do not want to have anything to do with javascript. Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Can DOM methods be native Function objects?
On 10/10/10, Mark S. Miller erig...@google.com wrote: On Mon, Oct 11, 2010 at 5:54 AM, Garrett Smith dhtmlkitc...@gmail.comwrote: [...] And that brings me to my next point: AIUI, host objects have two types. We discussed this before... (searching archives...) | The specification allows for two types of host objects: | * host objects as native objects | * host objects as not native objects (does not use | native semantics) Link please? IIRC, this part of the conversation was subsequently falsified. host and native are disjoint. host simply means not native. The first bullet above makes no sense. You disagreed with Allen's explanation: http://www.mail-archive.com/es-discuss@mozilla.org/msg04565.html -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Can DOM methods be native Function objects?
On 10/10/10, Brendan Eich bren...@mozilla.com wrote: On Oct 10, 2010, at 4:14 PM, Mark S. Miller wrote: My interpretation is that the spec in this regard is consistent with reality as intended and is not an ass. (Somewhat disconcerting to hear hints of the spec being called an ass.) Could be -- I know we have discussed this before, and I like your interpretation, but Cameron is only the latest among many to reach different categorical conclusions, which did not include yours (if I have not misread his). Something is unclear in the spec. /be Native functions can be written in JS or be built in. The semantics defined by the spec does not mean that the spec says what specifically their internal [[Call]] method does when called. Well duh! It does say what the overall contract is. For example, it must inherit from Function.prototype. It must have an integer length. It must have a [[Call]] property, and thus its typeof must be function. And it should have a [[Class]] of Function. Yes, we've discussed this before. In other words, [[Class]] Function is one of the native internal nominal types whose contract is defined by the spec. If a method of a host object obeys that contract, it would be best for it to actually be a native function. If a host method obeys that contract, how could one determine if it were not a native function? I think maybe if you want to say that host methods should be just specified as functions, where that makes sense. Because then you know you have a function, and thus a length property, [[Call]] property, etc. Some implementations have callable host objects that don't need to be functions, e.g. document.images, which in many implementations is callable as document.images(0) but is not a function. On Mon, Oct 11, 2010 at 12:41 AM, Brendan Eich bren...@mozilla.org wrote: On Oct 10, 2010, at 3:28 PM, Brendan Eich wrote: Native functions do not have associated FunctionBody representations, of course; one clue is what toString returns. Here I use native functions to mean either the built-in functions of ES5 clause 15, or the DOM built-in functions. Are the DOM functions considered built-in functions or host methods? Now I always considered them build-ins because A built-in object is any object supplied by an ECMAScript implementation. AIUI, DOM objects are not defined by the ECMAScript implementation, /though their semantics may be/ (native host object). And that brings me to my next point: AIUI, host objects have two types. We discussed this before... (searching archives...) | The specification allows for two types of host objects: | * host objects as native objects | * host objects as not native objects (does not use | native semantics) and | While the specification does not preclude the possibility that a host | object may be implemented with native semantics, it nonetheless | defines a host object: From thread [[Class]] Property of Host Object. Although the spec draws a bright line around its built-ins vs. host objects, real implementations use the same native-function variant of function objects for both. This is important reality to support with some spec fixes. Any DOM host object specified to be a native ES object can be expected to follow native semantics. What are you hoping to fix? -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Can DOM methods be native Function objects?
On 10/10/10, Garrett Smith dhtmlkitc...@gmail.com wrote: On 10/10/10, Brendan Eich bren...@mozilla.com wrote: On Oct 10, 2010, at 4:14 PM, Mark S. Miller wrote: [...] Here I use native functions to mean either the built-in functions of ES5 clause 15, or the DOM built-in functions. Are the DOM functions considered built-in functions or host methods? Now I always considered them build-ins because No! I wrote the opposite of what I really meant. I always considered them to be host objects, *not* built-ins. Sorry! A built-in object is any object supplied by an ECMAScript implementation. AIUI, DOM objects are not defined by the ECMAScript implementation, /though their semantics may be/ (native host object). Right; that's what I meant. [...] -- Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Rationalizing ASI (was: simple shorter function syntax)
On 7/25/10, Mark S. Miller erig...@google.com wrote: On Sun, Jul 25, 2010 at 11:36 AM, Brendan Eich bren...@mozilla.com wrote: On Jul 25, 2010, at 10:52 AM, Mark S. Miller wrote: The problem is that as long as ASI exists, one will often see working code such as this, since it does usually work. This training of the eye is a kind of habituation, and in this case it is insidious because it desensitizes the programmer from a pattern that *should* look malformed but doesn't. Ok, I'll grant you ASI desensitization is a factor in human readers missing this kind of bug. In the absence of ASI, such code would never normally appear in running code. Come on! Never (normally doesn't count, it's just hedging in a way that tends to assume the conclusion) must mean that if only we didn't suffer from ASI-based desensitization to missing semicolons, we would have perfect manual semicolon insertion and perfect code auditing and testing. But utopia is not an option. This hazard is insidious because testing may fail to uncover it, since tests have bugs too, test coverage is never perfect, and what's more, if the function expression itself returns a similar enough function, the caller of the stored method might not notice any malfunction. So let's agree on less often -- not never. Sure. When it does appear in running code, that should alert the programmer that their program violates their intention and needs to be fixed. That's nice, but should is not good enough. Empirically, it doesn't work that way. I'm not just going by my experience, but by the jibbering page, the bug reports I've seen, the Dojo guys who do use semicolons still having to ward off this hazard with a leading ; in each source file. Let's not go in circles. I claim: * The horses are long gone from the barn. * The mistake is easy to overlook even for JS coders who do use semicolons. * The trade-off of banning ASI rule 1 first bullet to reduce desensitization and eventually reduce the incidence of this kind of bug is not a clear win, vs. migration tax into Harmony and usability problems even writing fresh code. In order to reliably remove this hazard, we would need to ban statements from starting with '('. Perhaps we should consider doing so. The problem there is the common module pattern (besides breaking uses with eval) (function(){ ... })(); A problem is that this module can become Arguments production in CallExpression (and possibly NewExpression, though less likely), depending on what comes before it (as in the asi.html example where global.name = mike); That is why some scripts (Dojo, for example) begin with a semicolon, as: ;(function(){ })(); Dojo does this, for example. If ASI is removed from strict mode, then a semicolon will not be inserted at the end of the input stream. If ASI were disabled, then developers would realize right away that the problem if the Expression from file1.js missing a semicolon were to result in an error. In that scenario, it wouldn't make sense to have CallExpression be a restricted production. Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [[Class]] Property of Host Object
On 7/22/10, Mark S. Miller erig...@google.com wrote: On Thu, Jul 22, 2010 at 11:16 PM, David Flanagan da...@davidflanagan.comwrote: Allen, The host vs. native distinction has long bothered me as well. Thanks for a particularly lucid explanation. In the next edition of the spec, perhaps you could go further and eliminate the use of the word host altogether, leaving you with only native objects and non-native objects. Then you don't have to say that host objects can be native, or non-native. Garrett, You could drop the confusing word host, too. If you invert the boolean sense of your function then you can call it isNativeObject() or isNativeValue() or just isNative(). Changing the name would not make it interoperable with all released IE versions. The problem of isNativeObject can mostly be avoided. [...] Fortunately, for this one, you can simply ask typeof o === 'function' Yes, and much shorter than David's example and it still only holds true in ES5 implementations, so not interoperable. The other consideration with David's example is if it is used with any library that adds Array.prototype.forEach, and many do. In that case, David's `isCallable` would return true for anything, even if it was not passed anything at all: Array.prototype.forEach = function(fun , context) { Now most of the time, web sites check first, as the examples on MDC have long advocated, however there are many copy'n'pastes of what I see on Twitter.com. I've posted this on comp.lang.javascript -- have you noticed this? http://a2.twimg.com/a/1279831293/javascripts/twitter.js (alternatively: http://a2.twimg.com/a/1279831293/javascripts/twitter.js?1279833486) // Source code for Twitter.com: if(!Array.forEach) { Array.prototype.forEach = function(D, E) { var C = E || window; for(var B=0, A = this.length; B A;++B) { D.call(C,this[B],B,this) } }; Array.prototype.map=function(... The same strategy was copy'n'pasted to the company CoTweet, also a jQuery shop. The source of this may be Twitter employee Dustin Diaz: http://www.dustindiaz.com/sugar-arrays/ The code seen on Twitter.com looks strikingly similar, using `window` as global object, using pre increment instead of post increment, not checking to see if it is a sparse as if(`i in this`){ ... }, yet it is different than Prototype's each. And so using David's 'isCallable', we could have var nothingIsCallable = isCallable(); // true on Twitter.com Same problem with Function.prototype.bind checks: function isCallable(obj) { try { Function.prototype.bind(obj, null); return true; } catch(ex) { return false; } } Harmony should differentiate between non-native and native objects. Constructs such as that should not be depended upon. Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [[Class]] Property of Host Object
On 7/18/10, Allen Wirfs-Brock allen.wirfs-br...@microsoft.com wrote: The more important issue is our intent regarding the definitions of host and native objects. First regarding, alert in IE. Historically it is what it is and nobody should make any assumptions concerning the future based upon previous versions of IE or what they have observed so for in IE9 preview builds. I I hope the same can be said for the bug related to catch clauses and scope in IE9. don't think there is any disagreement that the [[class]] of alert should be 'Function'. However, if you want to pin that down in a standard then WebIDL is probably the place you need to do it. What is the basis for making assertions of what the [[Class]] for any host object should be? [...] So essentially, they are two kinds of host objects: native host objects and non-native host objects. The spec. doesn't explicitly talk about native host objects because their hostness is semantically irrelevant if they are also native. While that is true for the purposes of the specification, it is not necessarily true for script authors. For any script wanting to define `isHostObject`, that script is going to be in a predicament. Hence, when the spec. talks about host objects in most cases it is really talking about non-native host objects in order to impose specific sematic constraints upon them. I believe that in most cases in the ES5 spec, host object should be read as meaning non-native host object. Again, if the specification definition of host object is correct -- and you have confirmed that it is -- then there are two types of host objects, native, and non-native. And in that case, the clause that mentions [[Class]] property must change as I initially suggested. [snip remainder] Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: [[Class]] Property of Host Object
On 7/16/10, Mark S. Miller erig...@google.com wrote: On Fri, Jul 16, 2010 at 9:54 PM, Garrett Smith dhtmlkitc...@gmail.comwrote: I have a question reqarding [[Class]] property as defined In ES5: | The value of the [[Class]] internal property of a host object | may be any String value except one of Arguments, Array, | Boolean, Date, Error, Function, JSON, Math, Number, | Object, RegExp, and String May it be something other than a string value? Or must it be a string value? It must be a string value. The specification says may. Why must a host object's class be none of the built-in classes listed? So that the [[Class]] property serve as a reliable nominal type check for the contract that the other internal properties and methods satisfy. This is used primarily within the spec itself. Previously, it wasn't clear what was meant when the spec said, for example, if F is a function. Now we clearly say if the [[Class]] of F is 'Function' if that's what we mean. I think I see the problem. What you really want to say there is: | The value of the [[Class]] internal property of any non-native host | object must be any String value except one of... Because that allows `alert` to be any native ECMAScript object (Function, Object, etc), while still letting it be defined as a host object and not violating that spec. Iff, however, following my proposed amendment, `alert` had [[Class]] Object, and it was not a native ES object (as in IE versions), then it would be a specification violation. But it is also used from JS. Host objects are exempt from most of the specific behaviors specified for specific kinds of native objects. Were a host object to be able to allege to be a kind of native object without behaving as that kind of native object behaves, that would be bad. This is not in the spec: without behaving as that kind of native object behaves While the specification does not preclude the possibility that a host object may be implemented with native semantics, it nonetheless defines a host object: | 4.3.8 | host object | object supplied by the host environment to complete the | execution environment of ECMAScript. | | NOTE Any object that is not native is a host object. And that means that `alert`, `window`, `document`, XMLHttpRequest, are all host objects. Whether or not those objects are implemented as native ECMAScript objects is another matter altogether. It seems the the spec is wrong and that you have misinterpreted it. I believe that instead it should be written: Implementations don't agree; when calling `Object.prototype.toString` with a host object, the result will often be one of those values. Object.prototype.toString.call(alert); results either [object Function] or [object Object]. That behavior is allowed in ES3, but why not in ES5? ES5 seems to defy what most (if not all) implementations do there. As far as ES5 is concerned, an implementation is perfectly allowed to have alert's [[Class]] be Function, iff alert on that platform is a function, i.e., behaves as a function is obligated to behave. In fact, I think that is the most reasonable choice. If alert on a given implementation is instead a host object, then it has almost no rules governing its behavior. We don't wish it to be able to claim otherwise. I have not yet seen any draft of the new WebIDL bindings for ES5. These may very well determine whether alert is a host object or a native function, as far as w3c specs are concerned. Either decision would be allowed by ES5. Some host objects including `alert` are implemented as a native ECMAScript objects (`alert instanceof Function`). In that case, the [[Class]] property should be Function. (alert instanceof Function) is not a reliable test in either direction. No of course not. A host object as well as a native non-function is perfectly free to inherit from Function.prototype and thus pass this test. And an actual function may be an instance of Function constructor from another frame and so fail the test. But yes, iff alert is indeed a native function, it's [[Class]] should be Function. Therein lies a contradiction: A host object here may be a function. Yet because it is a host object, that same object's [[Class]] must not be Function, and yet again, since it is a function, and any function must have [[Class]] Function, then this object's [[Class]] must be Function. However according to ES5 specs, any host object must not be withing the set of values that are not allowable and so the assertion could be made that if any object has a [[Class]] that is one of those values, then the object is not a host object. Yes, that is intentional. Then it will fail today, as javascript: alert(({}).toString.call(alert)) - will result [object Object] or [object Function] Surely you meant _toString.call(m)? And of the two names above, I think Yes. asHostObject is more appropriate, as it applies whether m
Re: [[Class]] Property of Host Object
On 7/17/10, Mark S. Miller erig...@google.com wrote: [+es5-discuss as a possible errata issue arises below] On Sat, Jul 17, 2010 at 12:37 AM, Garrett Smith dhtmlkitc...@gmail.comwrote: On 7/16/10, Mark S. Miller erig...@google.com wrote: On Fri, Jul 16, 2010 at 9:54 PM, Garrett Smith dhtmlkitc...@gmail.comwrote: I have a question reqarding [[Class]] property as defined In ES5: | The value of the [[Class]] internal property of a host object | may be any String value except one of Arguments, Array, | Boolean, Date, Error, Function, JSON, Math, Number, | Object, RegExp, and String May it be something other than a string value? Or must it be a string value? It must be a string value. The specification says may. Ah. I see the ambiguity. may there is modifying any. It should probably have been stated: ...must be a String value and may be any String value except... In reviewing the document, the possibility that text would allow non-String [[Class]]es had not occurred to me. Now that you point it out, and can see some reasons why we might want to leave the current text alone and allow non-String [[Class]]es. I don't. [[Class]] must be a string value. If the [[Class]] property is absent, what happens when the object is supplied to Object.prototype.toString? TypeError. Why not avoid that possibility and require host object to have [[Class]] be a string value? Why must a host object's class be none of the built-in classes listed? So that the [[Class]] property serve as a reliable nominal type check for the contract that the other internal properties and methods satisfy. This is used primarily within the spec itself. Previously, it wasn't clear what was meant when the spec said, for example, if F is a function. Now we clearly say if the [[Class]] of F is 'Function' if that's what we mean. I think I see the problem. What you really want to say there is: | The value of the [[Class]] internal property of any non-native host | object must be any String value except one of... Saying non-native and host together is redundant. Although the language of 4.3.6 and 4.3.8 is not as clear as it should be, I read these as stating that all EcmaScript objects are either host or native. No object can be both host and native. And no object can be neither host nor native. It is not redundant. Repeating what was written in my last message: | While the specification does not preclude the possibility that a host | object may be implemented with native semantics, it nonetheless | defines a host object: I understand that the values for [[Class]] are used internally by the specification. One example of that is Array.isArray(x), where the [[Class]] property is used internally. Another example is behavior for `JSON` reviver. The specification allows for two types of host objects: * host objects as native objects * host objects as not native objects (does not use native semantics) From the implementors point of view, what matters the ability derive an inference from [[Class]]; if [[Class]] is x then [action]. However, from a programmer's perspective, `Object.prototype.toString.call(x)` cannot discriminate between objects originating in the host environment (what is currently defined as host object) and native objects. Mostly they shouldn't care, but should follow the specification approach to derive [[Class]] based inference, however they can't follow that because that is not compatible with existing implementations (notably IE versions and Opera (which copied IE)), and making an isStrict supported global flag is not going to provide a closely related inference about various types of host objects across a wide range of implementations in the wild. Internet Explorer 9 host objects seem to be absent of problems seen in previous versions of IE but there are still host objects that are callable, have [[Class]] Object, and are not implemented with native semantics. Two examples of such object are alert and addEventListener. Because that allows `alert` to be any native ECMAScript object (Function, Object, etc), while still letting it be defined as a host object and not violating that spec. that spec? What specification demands that alert be a host object? I have I cited 4.3.8; the definition of host object. not heard of any. This might be a consequence of the upcoming WebIDL-to-ES5 language bindings, but I have seen no draft and so have no idea. My own preference would be for these language bindings to result in alert being a native Function, but that's an argument for a different standards committee ;). If an implementation's alert is a Function, then it is a native object and its [[Class]] must be Function. It can still be an object provided by a host environment whose [[Call]] behavior is written in C++. This simply makes it a host provided native built-in object (4.3.7), not a host object. No, alert
[[Class]] Property of Host Object
I have a question reqarding [[Class]] property as defined In ES5: | The value of the [[Class]] internal property of a host object | may be any String value except one of Arguments, Array, | Boolean, Date, Error, Function, JSON, Math, Number, | Object, RegExp, and String May it be something other than a string value? Or must it be a string value? Why must a host object's class be none of the built-in classes listed? Implementations don't agree; when calling `Object.prototype.toString` with a host object, the result will often be one of those values. Object.prototype.toString.call(alert); results either [object Function] or [object Object]. That behavior is allowed in ES3, but why not in ES5? ES5 seems to defy what most (if not all) implementations do there. Some host objects including `alert` are implemented as a native ECMAScript objects (`alert instanceof Function`). In that case, the [[Class]] property should be Function. However according to ES5 specs, any host object must not be withing the set of values that are not allowable and so the assertion could be made that if any object has a [[Class]] that is one of those values, then the object is not a host object. An `isHostObject` method could be written using a RegExp: // DO NOT USE var _toString = Object.prototype.toString, nativeClasses = /Array|Boolean|Date|Error|Function|JSON|Math|Number|Object|RegExp|String/; function isHostMethod(m) { return !nativeClasses.test(.call(m)); } However, we know that won't hold true in many cases more than just `alert`. Is the specification wrong here or what am I missing? Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: RE: JSON parser grammar
On 6/3/09, Douglas Crockford doug...@crockford.com wrote: Allen Wirfs-Brock wrote: JSON.parse([010]) should be an error, per spec. Nobody follows the spec though... As I read them neither the RFC or the current ES5 JSON grammar recognize [010] as a valid JSON form, so according to the ES5 spec. a syntax error should be thrown. If we really want all implementation to accept 010 as a JSONNumber then we should specify it as such. Of course we have to define what it means (decimal, octal??). My inclination would be to require ES5 implementation to exactly conform the whatever JSON grammar we provide and to throw syntax errors if the input doesn't exactly conform to the grammar. (in other say that the section 16 extension allowance doesn't apply to JSON.parse. If an implementation wants to support JSON syntax extensions it could always do so by providing a JSON.parseExtended function (or whatever they want to call it) that uses an implementation defined grammar. I agree. It is not helpful to developers to allow weird forms on browser A but not on browser B. What should be allowed is clearly described in the E5 spec. On 6/3/09, Douglas Crockford doug...@crockford.com wrote: Allen Wirfs-Brock wrote: JSON.parse([010]) should be an error, per spec. Nobody follows the spec though... As I read them neither the RFC or the current ES5 JSON grammar recognize [010] as a valid JSON form, so according to the ES5 spec. a syntax error should be thrown. If we really want all implementation to accept 010 as a JSONNumber then we should specify it as such. Of course we have to define what it means (decimal, octal??). My inclination would be to require ES5 implementation to exactly conform the whatever JSON grammar we provide and to throw syntax errors if the input doesn't exactly conform to the grammar. (in other say that the section 16 extension allowance doesn't apply to JSON.parse. If an implementation wants to support JSON syntax extensions it could always do so by providing a JSON.parseExtended function (or whatever they want to call it) that uses an implementation defined grammar. I agree. It is not helpful to developers to allow weird forms on browser A but not on browser B. What should be allowed is clearly described in the E5 spec. That's right. A wrapper for JSON should be consistent and if native JSON support isn't, then what does the wrapper do, follow the ES5 spec or follow what the browsers do? What if no browsers follow the spec? Does that mean we can't use native JSON at all? The wrapper can use capability checks to determine if native JSON is buggy and if it is, use a fallback. I've provided a sample capability test below, for those who don't know what I mean. Most of the questions on Grammar were answered in this thread, however, the question of U+0009 as a JSONStringCharacter remains. All major browsers allowi U+0009 in JSONString. What should the capability test check? If all major browsers parse without error ' \t ' to result in a string with the character U+0009, then the feature test can detect that failing and use the fallback. JSON.parse accepting U+0009 in strings is now part of public API and major libraries rely on that. Is going to be codified? To summarize, the pressing questions are: 1) Is the spec going to change to allow U+0009? And if it isn't, why not? and 2) What should the fallback for JSON.parse use? Should it: (a) go by the letter of the spec and perform a capability test to expect that an error is thrown for JSON.parse(' \t '), or (b) go with what seems to be a de facto standard and allow U+0009 as JSONStringCharacter? There is a need to answer these questions so that code can be written using JSON. It's not just an academic exercise here. I would like to provide an advisable solution as an FAQ Entry the comp.lang.javascript FAQ. Example of a feature test: // Incomplete and untested. var IS_JSON_PARSE_SUPPORTED = function() { var IS_JSON_PARSE_SUPPORTED = typeof JSON == object typeof JSON.parse == function isJSONParserCompliant(); function isJSONParserCompliant() { // TODO: add more checks for known failings // in major implementations. return canParseNumbers(); } function canParseNumbers() { try { JSON.parse(010); return false; // error expected. } catch(ex) { } return true; } return IS_JSON_PARSE_SUPPORTED; }(); Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: JSON parser grammar
On 6/22/10, Luke Smith lsm...@lucassmith.name wrote: On Jun 22, 2010, at 7:20 PM, Oliver Hunt wrote: On Jun 22, 2010, at 7:07 PM, Dean Landolt wrote: On Tue, Jun 22, 2010 at 9:34 PM, Oliver Hunt oli...@apple.com wrote: [...] As far as I can tell, all the major browsers accept tabs, as do many other json parsers, at brief inspection it seems that the defacto (vs. actual) JSON spec allows tabs. Most but not all. Look: IE9b and BESEN (though not a browser) both throw SyntaxError on U+0009 in JSONString: alert( JSON.parse(' \t ') ); (error message in IE9 says: Invalid Character.) And regarding js library abstractions, I disagree that there is enough stability in the JSON implementations to state that major libraries *rely* on the parsing of tabs. I think tolerate is closer to the truth. I certainly do not rely on native implementations continuing not to conform to a spec that, relatively speaking, is fresh out of the gate. I would rather see the implementations get cleaned up and follow spec than agree this early to disregard it. Prototype and jQuery don't check to make sure the string doesn't contain \0-\x1f. json2.js doesn't and I would not be surprised if other libraries didn't either. Basically, these scripts do minimal feature tests on global JSON (json2.js merely checks for existence). If global JSON exists, it is used, and if it does not exist, then a fallback is used. The result can be guaranteed to be widely inconsistent depending on the browser, version, and in IE, even document mode. Any application that uses any library that uses unfiltered JSON.parse or json2.js may be expecting TAB to continue to work so changing that will probably break things for some environments. I can see why implementations might want to allow TAB, and most major browsers do, despite the fact that such extensions are explicitly forbidden. I mean, I can see why Opera would allow \t in JSONString because otherwise, people would be complaining it doesn't work in Opera. Having varied behavior depending on the environment and the input supplied to JSON.parse is no good and having a de facto standard that contradicts the spec is no good. | 15.12 The JSON Object | | [...] | | Conforming implementations of JSON.parse and JSON.stringify must support | the exact interchange format described in this specification without any deletions | or extensions to the format. This differs from RFC 4627 which permits a | JSON parser to accept non-JSON forms and extensions. If all major implementations are going to start disallowing U+0009 in JSONString -- and according to what Doug wrote earlier today they are -- then the spec can stay as-is. Otherwise, if major implementations want to allow \t in JSONString, then they should argue for that case here and argue that the spec be changed and if they lose that argument, then they must not continue to violate the spec. Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: JSONNumber - optional decimal
On 6/10/10, Sigbjorn Finne sigbjorn.fi...@gmail.com wrote: Hi Garrett, On 6/9/2010 05:46, Garrett Smith wrote: ... IF anyone has a correct JSON parser, I would appreciate it. Also, are there any good test suites for JSON? http://testsuites.opera.com/JSON/ is one. Hallvord Steen has a good blog post on it, http://my.opera.com/core/blog/2009/12/18/native-json-support-in-opera Predates Carakan by a couple of weeks, so the Opera perf numbers are a bit dated by now. hth It would be really useful to have the test as a zip file so it could be downloaded and run locally. I've identified five bugs in json2.js' JSON.parse and I want to address those. I suspect more could be found with a test suite for JSON.parse (no reviver). The Opera test functions start running automatically. It would be nice to have a start button and placed next to that a warning that the test may freeze or crash internet explorer 8 (as it happened to me). With a start button, I would at least have the hacking ability to say, for example, type into the location bar: javascript: addMyJSONScript(); void (JSON.parse = MyJSON.parse) and then hit enter, and then hit the start button on the test runner. That kind of sucks, though. Really what I want is a testsuite that I can download and run. I've also noticed that the test runner uses sync request. This can be a problem if the test fails to load. Instead, it should use async requests or iframes or something -- so long as it is not known to lock up the browser. Perhaps that is what caused the freeze in IE (or was it the performance test that was too intensive?) Also, I noticed in the blog entry: | TAB characters may not appear inside strings | - {tab:there is a tab - - here} is wrong! | The spec requires using \t instead of a literal TAB character. The blog entry goes on about on how TAB character is not allowed in strings. Where in the spec is it stated that literal TAB characters in strings are disallowed? http://my.opera.com/core/blog/2009/12/18/native-json-support-in-opera Finally, I'd like mention the buggy implementations that have been released: Firefox and IE. Having to devise feature tests for every known implementation failure case requires the developer first gather known failures. He must do this by testing all the implementations that he can, and, for each found failure, provide a feature test in the adapter script he is writing and where that feature test fails, provide a fallback to his own implementation.That's a lot of burden on the developer. Instead, I'd much rather see open test suites where implementations would collaborate and release consistent, standard features. Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: JSONNumber - optional decimal
On 6/8/10, Oliver Hunt oli...@apple.com wrote: On Jun 8, 2010, at 8:46 PM, Garrett Smith wrote: [...] IF anyone has a correct JSON parser, I would appreciate it. Also, are there any good test suites for JSON? I spent quite a bit of time ensuring JSC's JSON parser exactly matched the spec grammar, and hence exhibits this behaviour so I believe the parser in JSC is correct -- if you're interested the code can be found at (note that it's under an MIT style license) http://trac.webkit.org/browser/trunk/JavaScriptCore/runtime/LiteralParser.cpp I see, so \d. is no good. I was more looking for a few regexps to fill in a tight function for the FAQ. While your C++ looks clean, transliterating that would surely be a no-go for the FAQ. Strategy-outline: // TODO: define validJSONExp. var parseJSON = NATIVE_JSON_PARSE_SUPPORT ? function(responseText) { return JSON.parse(responseText); } : function(responseText) { if(validJSONExp.test(responseText)) { return new Function(return( + responseText + ))(); } else { throw SyntaxError(JSON parse error); } }; The goal is to essentially match exactly what JSON parse would do for 1 argument and for the FAQ, the code would be tighter to use a RegExp. I'll figure it out. At the time I recall talking a bit with Hallvord Steen of Opera, and he was working on a testsuite of some sort but I can no longer recall the url. OK. Good to know. That said I think allowing '1.' (etc) makes sense as it's fairly standard across multiple programming languages, and I am unaware of any specific reason for disallowing it. It seems like it would have made sense. Now, well, no, not now; the spec is released and implemented like that in at least two implementations. In the long term I don't see changing the grammar to allow a trailing period as being harmful as it's a relaxation. In the short term vendors that follow the spec may fail to parse content :-( Changing it now would probably just create more confusion. ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
JSONNumber - optional decimal
Today I looked for a good json regexp tester and finding nothing, decided to write one. The strategy that occurred to me was to first define a regex for the literal components (ES5 lumps literal value into the JSONValue alongside JSONObject and JSONArray). That way, I could reuse the literal components to define JSONObject and JSONArray. In the process, I noticed that the grammar defined for JSONNumber is different than that defiend by json2.js, which I had just looked at, and which has similar numeric parsing as seen in The GOod parts. That is, it allows DecimalLiteral, which includes this production: DecimalIntegerLiteral . In contrast, JSONNumber does not allow that. JSONNumber :: -opt DecimalIntegerLiteral JSONFractionopt ExponentPartopt Am I misreading the spec, or is 1. not valid JSON? Next step was to see what the browsers do. Mozilla and IE accept it, while Webkit and Opera throws an error. JSON.parse(1.) Firefox 3.6, IE8, Besen r27: 1 Safari, Opera SyntaxError IF anyone has a correct JSON parser, I would appreciate it. Also, are there any good test suites for JSON? Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Adoption of the Typed Array Specification
On Thu, May 13, 2010 at 5:34 PM, Mark S. Miller erig...@google.com wrote: On Thu, May 13, 2010 at 5:15 PM, Vladimir Vukicevic vladi...@mozilla.com wrote: This is difficult to do, given the goals of typed arrays -- they wouldn't behave like normal Arrays in most meaningful ways. At the core, an ArrayBuffer is of fixed size, and it doesn't make sense to index an ArrayBuffer directly (because there's no indication of what format the data should be accessed in). Making the array view types instances of Array might work, but again given that they're fixed length, there's a significant difference there. in ES5: var x = []; for (var i = 0; i N; i++) { x.push(0); } Object.seal(x); That is verbose. The x that results from the above code is fully populated, of fixed length, and must remain fully populated. It is much closer to what programmers coming from other languages might regard as an array. A FixedArrayLiteral would be better but the language does not have such construct. var noElisions = [ length:N, sealed: true ]; ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Where to Report Spec Errata?
On Mon, May 10, 2010 at 11:18 AM, Allen Wirfs-Brock allen.wirfs-br...@microsoft.com wrote: Function.prototype.toString - s/FunctionDeclaration/FunctionExpression. This is not an error. FunctionDeclaration is intentional and is traceable back to the ES1 spec. There was discussion on this topic on es-discuss but there was no clear consensus on making this specific change or any of the alternatives that were discussed. It was discussed and the specification states that a representation of a FunctionDeclaration is returned. This is not an editorial bug, but a specification of behavior that implementations violate, with reason, and will continue to violate in the case of anonymous functions: var fString = (function(){}).toString(); None of the major implementations return a FunctionDeclaration representation. Are all implementations wrong or is the spec wrong? I don't want to go on like a broken record, reiterating the same arguments. It seems this issue could go on a bug tracker where it could either be accepted or marked INVALID. Error instances have a message property, but it is not specified (as mentioned previously) This is not an error, the 'message' property is defined in 15.11.4.3 as a property of Error.prototype (which all defined error instances inherit from) and 15.11.1.1 and 15.11.2.1 makes it clear that the message value specified when creating an error object is used to set the own 'message' property of the new object (and hence over-rides the inherited 'message' property. Arguably, it would be more consistent with the organization of the rest of Chapter 15 if 'message' and 'name' were defined in 15.11.5 but that would not change any actual requirements defined by the specification. This is neither a technical issue nor a actual editorial 'bug' (such as a misspelling) so it really doesn't belong in the ES5 errata. (The purposwe of the errata is to list actual unintended bugs in the document, not to serve as the first working draft of the next edition). Error instance properties: I see where Error message instance is set when the Error constructor is called. I also agree that it would be clearer to have `message` and `name` mentioned in 15.11.5 compared to what is there now: | 15.11.5 Error instances have no special properties. Sounds like there is an Errata document in the works. Will that be published on ecma-international.org? I was not proposing the RegExp or top level Array generics go in an Errata document -- that's not what was meant. They are interesting and useful proposals, though, along with catchalls proposal. RegularExpressionLiteral is missing from Annex A.1 Lexical Grammar Ok, got it. Allen -Original Message- From: es-discuss-boun...@mozilla.org [mailto:es-discuss- boun...@mozilla.org] On Behalf Of Garrett Smith Sent: Sunday, May 09, 2010 4:32 PM To: Mark S. Miller Cc: es5-disc...@mozilla.org; es-discuss; Erik Arvidsson Subject: Re: Where to Report Spec Errata? On Sun, May 9, 2010 at 3:56 PM, Mark S. Miller erig...@google.com wrote: On Sun, May 9, 2010 at 3:50 PM, Erik Arvidsson erik.arvids...@gmail.com wrote: On Sun, May 9, 2010 at 15:19, Garrett Smith dhtmlkitc...@gmail.com wrote: Where is the right place to report errata in the ES5 specification? This mailing list. For ES5 errata, please send to es5-discuss as well. OK. A formal bugtracker has some advantages, too. Can organize, prioritize bugs and feature requests, add comments, testcases. Buglist: Function.prototype.toString - s/FunctionDeclaration/FunctionExpression. Error instances have a message property, but it is not specified (as mentioned previously) RegularExpressionLiteral is missing from Annex A.1 Lexical Grammar Wishlist: A bugtracker (just one) for Harmony and ES5 Error stack, either instance property or as a getter on Error.prototype Top level Array Generics Other interesting proposals: Regex feature requests from Steve Levithan's Regex pages http://blog.stevenlevithan.com/archives/fixing-javascript-regexp ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Where to Report Spec Errata?
Where is the right place to report errata in the ES5 specification? ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Where to Report Spec Errata?
On Sun, May 9, 2010 at 3:56 PM, Mark S. Miller erig...@google.com wrote: On Sun, May 9, 2010 at 3:50 PM, Erik Arvidsson erik.arvids...@gmail.com wrote: On Sun, May 9, 2010 at 15:19, Garrett Smith dhtmlkitc...@gmail.com wrote: Where is the right place to report errata in the ES5 specification? This mailing list. For ES5 errata, please send to es5-discuss as well. OK. A formal bugtracker has some advantages, too. Can organize, prioritize bugs and feature requests, add comments, testcases. Buglist: Function.prototype.toString - s/FunctionDeclaration/FunctionExpression. Error instances have a message property, but it is not specified (as mentioned previously) RegularExpressionLiteral is missing from Annex A.1 Lexical Grammar Wishlist: A bugtracker (just one) for Harmony and ES5 Error stack, either instance property or as a getter on Error.prototype Top level Array Generics Other interesting proposals: Regex feature requests from Steve Levithan's Regex pages http://blog.stevenlevithan.com/archives/fixing-javascript-regexp ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Function.prototype.bind
On Sat, May 1, 2010 at 7:13 AM, Brendan Eich bren...@mozilla.com wrote: On May 1, 2010, at 3:28 AM, Jürg Lehni wrote: On 1 May 2010, at 01:50, Brendan Eich wrote: [...] Odd, that is neither fish nor fowl. Does any other library have such a bind? Anyway, Moo was not around when TC39 was looking at bind, or at least, it was not on our radar. YUI had bind that did a right bind. From a glance it looks like that functionality is changed, and I see they now have a function called rbind. Ext.js has a flag for their bind function to use either right bind or left bind. ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Function.prototype.bind
On Fri, Apr 30, 2010 at 11:07 PM, Brendan Eich bren...@mozilla.com wrote: On Apr 30, 2010, at 10:28 PM, Garrett Smith wrote: It could be that we missed a chance to add Function.bind(callable, thisObj, argsArray). Adding such a static method might have provided the desired common utility usable without conflicts by libraries. We may yet add such a Function.bind. Function.bind is already specified, isn't it? Function itself is a function. Oops, of course -- it would have to be called something else, or located somewhere else. Yeah, a different name, if at all. Static Array Generics don't have that problem, though, e.g. Array.slice(hostObj) ... Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: Function.prototype.bind
On Fri, Apr 30, 2010 at 5:50 PM, Brendan Eich bren...@mozilla.com wrote: On Apr 30, 2010, at 5:33 PM, Jürg Lehni wrote: [...] Yes, jQuery nicely avoids the whole prototype issue. What do the spec contributors have to say about scripts that modify built-ins? The concept don't modify objects you don't own can be a hot topic for some. What does the committee have to say on that? Mentioned in elsehwere: http://jibbering.com/faq/notes/code-guidelines/ http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/ [...] It could be that we missed a chance to add Function.bind(callable, thisObj, argsArray). Adding such a static method might have provided the desired common utility usable without conflicts by libraries. We may yet add such a Function.bind. Function.bind is already specified, isn't it? Function itself is a function. [...] Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss
Re: three small proposals: the bikeshed cometh!
On Thu, Apr 29, 2010 at 12:25 AM, Alex Russell a...@dojotoolkit.org wrote: Some small, pre-colored panels for the shed. Given that these are mostly matters of syntax and not semantics, please believe me when I suggest that the warts discussed herein present sharp edges that should be rounded off by the committee -- not because they're interesting in any way but because the primary users of the language are shipping (bad) fixes around the network billions of times a day. Such rank inefficiency needs sunset date. Summary of proposals: - // 1.) Really generic generics ArrSubtype = function() { }; ArrSubtype.prototype = Object.create(Array.prototype); var nas = new ArrSubtype(); nas.push(howdy, pardner); nas.slice(0) instanceof Array; // currently true nas.slice(0) instanceof ArrSubtype; // will be true after fix The Array prototype methods are not going to change the return type. Doing that would break any existing code that is trying to use array generics and expecting the `this` value to be an array. // 2.) Shorthand for function, aka the not lambda node.addEventListener(click, #(e){ e.preventDefault(); }); node.removeEventListener(click obj!#(e){ ... }); // see #3 That would be possible so long as it does not conflict with existing syntax. AFAIK, # is used in Spidermonkey for recursive object literal notation: #1={a:#1#} - however it would not seem to conflict here. [...] Discussion: --- 1.) Really generic generics Methods on Array.prototype that today return instances of Array should instead return instances of whatever subtype begat them. Assume that the DOM sucked less and that NodeList instances were subtypes of Array. In that case, we should be able to do something like: If a thought about code cannot be explained using correct terminology, then it is not very well understood by the person doing the explaining. I inferred from your example that you meant an object that has Array.prototype in its prototype chain. The use of nonstandard terminology to describe ECMAScript tends to harbor misconceptions about the language. On that, NodeList is not - and should not be - an Array. The two concepts should be understood independently before attempting to use them. This very subject was just discussed on WHAT WG list. Did you see it? Here is the last message: http://www.mail-archive.com/wha...@lists.whatwg.org/msg21131.html Elsewhere: whatwg] WebIDL and HTML5 http://lists.w3.org/Archives/Public/public-webapps/2008JulSep/0480.html NodeList.prototype.parents = function() { // should return a NodeList return this.map(function(n) { return n.parentNode; }); } document.querySelectorAll(p).slice(2).parents().filter(...); Today, the only way for subtypes to use these generics is to wrap or re-implement them. The functions that need to be fixed include: No functions need to be included. [...] 2.) Function shorthand [snip] Many functions, both in the DOM and in the library, accept functions as arguments. ES5 provides a bind() method that can ease the use of these functions when the passed method comes from an object. This is, however, inconvenient. E.g.: node.addEventListener(click, obj.method.bind(obj, ...)); Also, insufficient. Event listeners can't be detached when using Function.prototype.bind: That is not true at all. I suggest reading the ES5 specifation that before proceeding. [...] Garrett ___ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss