<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0"><id>tag:blogger.com,1999:blog-34454975</id><updated>2012-02-10T11:38:03.698+01:00</updated><category term="VBScript" /><category term="cipher" /><category term="Visual Studio" /><category term="protocol" /><category term="solution" /><category term="super" /><category term="literal" /><category term="bug" /><category term="140" /><category term="crystal" /><category term="ArrayObject" /><category term="CommonJS" /><category term="String" /><category term="on" /><category term="conversion" /><category term="new" /><category term="revisited" /><category term="proposal" /><category term="hghlight" /><category term="ElseIf" /><category term="require" /><category term="getElementsByClassName" /><category term="Apple" /><category term="upgrade" /><category term="JavaScript.XML" /><category term="Code" /><category term="make" /><category term="detection" /><category term="with" /><category term="N510" /><category term="not" /><category term="thoughts" /><category term="FatalError" /><category term="SPL" /><category term="Yahtzee" /><category term="defects" /><category term="mini" /><category term="Laptop" /><category term="write" /><category term="evil" /><category term="Apache" /><category term="xhtml" /><category term="setImmediate" /><category term="closures" /><category term="minifier" /><category term="friendly" /><category term="opera" /><category term="sort" /><category term="scripting" /><category term="recycle" /><category term="gif" /><category term="distributed" /><category term="type" /><category term="Shaders" /><category term="XSL" /><category term="Fart" /><category term="Hunspell" /><category term="CSS" /><category term="talk" /><category term="Unit Test" /><category term="in" /><category term="delirium" /><category term="Christmas" /><category term="leak" /><category term="hybrid" /><category term="effect" /><category term="exposed" /><category term="trim" /><category term="yal.js" /><category term="experiment" /><category term="OSX" /><category term="UK" /><category term="writable" /><category term="Elsewhere" /><category term="Dash" /><category term="anonymous" /><category term="bytes" /><category term="JavaScirpt" /><category term="Array" /><category term="LAB.js" /><category term="JSON.hpack" /><category term="obtrusive" /><category term="JSONH" /><category term="2.0" /><category term="power" /><category term="lightweight" /><category term="design" /><category term="Internet Explorer" /><category term="ubuntu" /><category term="CDN" /><category term="notification" /><category term="convertion" /><category term="Sizzle" /><category term="prevent" /><category term="compiler" /><category term="BJSpell" /><category term="this" /><category term="Aptana" /><category term="Internet Epxlorer" /><category term="Microsoft" /><category term="best" /><category term="ES6" /><category term="sessionStorage" /><category term="debugger" /><category term="W3C" /><category term="serialization" /><category term="jQuery UI" /><category term="SWF" /><category term="demo" /><category term="FX" /><category term="Harmony" /><category term="PAMPA-J" /><category term="define" /><category term="ctypes" /><category term="node" /><category term="response" /><category term="indexOf" /><category term="frameworks" /><category term="Chrome" /><category term="markdown" /><category term="plugin" /><category term="Framework" /><category term="defineHybridProperty" /><category term="compressed" /><category term="new year" /><category term="Batch" /><category term="transitions" /><category term="transformer" /><category term="_super" /><category term="toISOString" /><category term="automator" /><category term="focus" /><category term="Object" /><category term="common" /><category term="cross" /><category term="tricks" /><category term="falsy" /><category term="JXON" /><category term="arrow" /><category term="IE6" /><category term="wru" /><category term="silverlight" /><category term="check" /><category term="constant" /><category term="fromCharCode" /><category term="area" /><category term="ASCII" /><category term="engine" /><category term="performances" /><category term="files" /><category term="size" /><category term="button" /><category term="ball" /><category term="readyState" /><category term="create" /><category term="Roundtable" /><category term="properties" /><category term="private" /><category term="JSLint" /><category term="Options" /><category term="PHP" /><category term="meta" /><category term="Mousetrap" /><category term="CoffeeShit" /><category term="interaction" /><category term="unload" /><category term="Ext JS" /><category term="CSS3" /><category term="Ruby" /><category term="getPrototypeOf" /><category term="log" /><category term="callee" /><category term="devpro.it" /><category term="outerHTML" /><category term="Frame" /><category term="Samsung" /><category term="jSmile" /><category term="intenret" /><category term="Sandbox" /><category term="expando" /><category term="assignment" /><category term="decimal" /><category term="Informations" /><category term="Pascal" /><category term="WorkerLocation" /><category term="btoa" /><category term="Unite" /><category term="mobile" /><category term="natural" /><category term="documentation" /><category term="html5" /><category term="characters" /><category term="Image" /><category term="C" /><category term="good" /><category term="imrovements" /><category term="relation" /><category term="method" /><category term="WebKit" /><category term="grant" /><category term="apply" /><category term="getElementsByTagName" /><category term="library" /><category term="convention" /><category term="Sprotector" /><category term="ES3" /><category term="IE10" /><category term="side" /><category term="base64" /><category term="Flash" /><category term="devices" /><category term="Trends" /><category term="save as" /><category term="standard" /><category term="Rhino" /><category term="function" /><category term="List" /><category term="isFunction" /><category term="injection" /><category term="EventEmitter" /><category term="swine flu" /><category term="limit" /><category term="banner" /><category term="safari" /><category term="broken" /><category term="Builder" /><category term="defineProperty" /><category term="jQuery" /><category term="defineProperties" /><category term="merits" /><category term="bad" /><category term="lightning" /><category term="attribute" /><category term="overload" /><category term="isCallable" /><category term="driven" /><category term="Revolution" /><category term="VS9" /><category term="scope" /><category term="MDC" /><category term="onload" /><category term="toolbar" /><category term="parody" /><category term="XML" /><category term="unpacked" /><category term="improvement" /><category term="dataset" /><category term="language" /><category term="Ten Grand" /><category term="advanced" /><category term="slickspeed" /><category term="filter" /><category term="correct" /><category term="Else" /><category term="javascript 2" /><category term="Listener" /><category term="style" /><category term="var_export" /><category term="Map" /><category term="emulation" /><category term="for in" /><category term="Observer" /><category term="region" /><category term="polyfills" /><category term="tuscany" /><category term="software" /><category term="errors" /><category term="ie7" /><category term="Multiton" /><category term="begetObject" /><category term="ES5" /><category term="bit.ly" /><category term="Levenshtein" /><category term="Io" /><category term="postable" /><category term="compressor" /><category term="prototype" /><category term="recursion" /><category term="implicit cast" /><category term="node.js" /><category term="Twitter" /><category term="unobtrusive" /><category term="GWT" /><category term="technologies" /><category term="inline" /><category term="YAGNI" /><category term="connection" /><category term="restaurant" /><category term="2011" /><category term="outline" /><category term="Date" /><category term="getAttribute" /><category term="fast" /><category term="UPDATE" /><category term="benchmark" /><category term="gzip" /><category term="Formaldehyde" /><category term="ambiguity" /><category term="User" /><category term="TechHub" /><category term="Jam" /><category term="console" /><category term="js-ctypes" /><category term="download" /><category term="TaskSpeed" /><category term="8601" /><category term="CPU" /><category term="browser" /><category term="EventListener" /><category term="monitor" /><category term="class" /><category term="Macro" /><category term="script" /><category term="Object.create" /><category term="background" /><category term="debug_backtrace" /><category term="file" /><category term="JavaScriptCore" /><category term="default" /><category term="Application" /><category term="tesla" /><category term="fatal" /><category term="debug" /><category term="use strict" /><category term="crash" /><category term="batman" /><category term="unserialize" /><category term="gzipped" /><category term="process" /><category term="patterns" /><category term="HTMLCollection" /><category term="stream" /><category term="essential" /><category term="random" /><category term="chain" /><category term="broadband" /><category term="reset" /><category term="PC Pro" /><category term="translator" /><category term="2010" /><category term="instance" /><category term="YUI" /><category term="API" /><category term="removeAttribute" /><category term="constructor" /><category term="enumerable" /><category term="C#" /><category term="source" /><category term="Algorithm" /><category term="tests" /><category term="blogger" /><category term="TreePanel" /><category term="Mootools" /><category term="RegExp" /><category term="fixed" /><category term="call" /><category term="Agent" /><category term="shared" /><category term="basis" /><category term="upload" /><category term="runtime" /><category term="Singleton" /><category term="structure" /><category term="features" /><category term="vice-versa" /><category term="yuno" /><category term="pattern" /><category term="VBClass" /><category term="maps" /><category term="Dart" /><category term="StringBuilder" /><category term="way" /><category term="valueOf" /><category term="scree" /><category term="avoid" /><category term="resize" /><category term="JSObject" /><category term="live" /><category term="arguments" /><category term="development" /><category term="privileged" /><category term="watch" /><category term="Ajaxian" /><category term="floor" /><category term="Berlin" /><category term="self" /><category term="Math" /><category term="events" /><category term="parsing" /><category term="Windows" /><category term="resolution" /><category term="partial" /><category term="buzz" /><category term="conflicts" /><category term="inheritance" /><category term="module" /><category term="Relator" /><category term="JsonTV" /><category term="O3D" /><category term="bookmarklet" /><category term="stand alone" /><category term="spam" /><category term="Expressions" /><category term="jsc" /><category term="prototypal" /><category term="deflate" /><category term="WebReflection" /><category term="italia.it" /><category term="draft 76" /><category term="transform" /><category term="loader" /><category term="ExtJS" /><category term="trimRight" /><category term="LiveMonitor" /><category term="font-face" /><category term="bridge" /><category term="example" /><category term="UX" /><category term="DELAYED" /><category term="setAttribute" /><category term="Subclass" /><category term="memory" /><category term="lambda" /><category term="NWMatcher" /><category term="native" /><category term="record" /><category term="server side" /><category term="beta" /><category term="JavaScript Hijacking" /><category term="read" /><category term="execution" /><category term="dojo" /><category term="iPhone" /><category term="text" /><category term="build" /><category term="280" /><category term="holidays" /><category term="practices" /><category term="optimization" /><category term="OOP" /><category term="responsive" /><category term="circle" /><category term="NHS" /><category term="Widget" /><category term="navigator" /><category term="grab" /><category term="epic" /><category term="binary safe" /><category term="project" /><category term="love" /><category term="content" /><category term="Event" /><category term="Python" /><category term="es4" /><category term="operator" /><category term="slice" /><category term="challenge" /><category term="no flash" /><category term="support" /><category term="JS1K" /><category term="client" /><category term="bin" /><category term="magic" /><category term="ISO" /><category term="JSConf" /><category term="XMLHttpRequest" /><category term="ActionScript" /><category term="eval" /><category term="input" /><category term="tag" /><category term="Portable" /><category term="London" /><category term="PyramiDOM" /><category term="Pure DOM" /><category term="instanceof" /><category term="png" /><category term="Libraries" /><category term="Object.createStatic" /><category term="PAMPA" /><category term="Spectrum" /><category term="Tokens" /><category term="Composite" /><category term="overloading" /><category term="no swf" /><category term="AMD" /><category term="access" /><category term="canvas" /><category term="textarea" /><category term="statement" /><category term="configurable" /><category term="classical" /><category term="Storage" /><category term="blocked" /><category term="Components" /><category term="Comet" /><category term="JSON" /><category term="comments" /><category term="Ad 2.0" /><category term="Factory" /><category term="URLs" /><category term="promotion" /><category term="Satay" /><category term="recovery" /><category term="embedded" /><category term="Konami" /><category term="speed" /><category term="sourceIndex" /><category term="MyMin" /><category term="$super" /><category term="homogeneous" /><category term="recruiters" /><category term="hpack" /><category term="tweetcode" /><category term="deployment" /><category term="5.3.5" /><category term="ellipse" /><category term="steal" /><category term="Stack" /><category term="post" /><category term="packed" /><category term="Google" /><category term="ie" /><category term="Set" /><category term="replace" /><category term="coercion" /><category term="Internet Explorer 8" /><category term="setInterval" /><category term="JavaScript.document" /><category term="host objects" /><category term="JsonReader" /><category term="closure" /><category term="WebGL" /><category term="extras" /><category term="server" /><category term="If" /><category term="questions" /><category term="AMF" /><category term="Serializable" /><category term="haxe" /><category term="problem" /><category term="Rebecca Murphey" /><category term="Adapter" /><category term="JS.next" /><category term="IE9" /><category term="fireEvent" /><category term="Strict" /><category term="3site.it" /><category term="INSERT" /><category term="parent" /><category term="getter" /><category term="isNative" /><category term="packed.it" /><category term="syntax" /><category term="sub" /><category term="JavaScript.PHP" /><category term="Web" /><category term="firefox" /><category term="test" /><category term="values" /><category term="KISS" /><category term="DOM" /><category term="window" /><category term="tips" /><category term="link" /><category term="advertisement" /><category term="JScript" /><category term="bind" /><category term="multiple" /><category term="future" /><category term="buttons" /><category term="Lion" /><category term="MySQL" /><category term="XSLT" /><category term="WebSocket" /><category term="Nokia" /><category term="security" /><category term="mistakes" /><category term="look" /><category term="Douglas Crockford" /><category term="extend" /><category term="Xpath" /><category term="__noSuchMethod__" /><category term="fuckn.es" /><category term="Collection" /><category term="nested" /><category term="editor" /><category term="YUICompressor" /><category term="protected" /><category term="custom" /><category term="JSONP" /><category term="CoffeeScript" /><category term="View" /><category term="bar" /><category term="Mouse" /><category term="escape" /><category term="Regular" /><category term="Tree" /><category term="base" /><category term="IE8" /><category term="Jaxer" /><category term="html" /><category term="EU" /><category term="scroll" /><category term="let" /><category term="quality" /><category term="selector" /><category term="fun" /><category term="trimLeft" /><category term="methods" /><category term="Phico" /><category term="encode" /><category term="JavaScript" /><category term="serialize" /><category term="request" /><category term="zlib" /><category term="uri" /><category term="ft2010" /><category term="out of order" /><category term="myth" /><category term="GeoLocation" /><category term="Template" /><category term="proxy" /><category term="asynchronous" /><category term="Sniff" /><category term="mock" /><category term="ECMAScript" /><category term="mjst" /><category term="load" /><category term="environment" /><category term="all" /><category term="unshared" /><category term="hart" /><category term="export" /><category term="Front" /><category term="cheat" /><category term="easy" /><category term="Ajax" /><category term="form" /><category term="compression" /><category term="LLVM" /><category term="bing" /><category term="toy" /><category term="is_a" /><category term="setter" /><category term="cross-browser" /><category term="__sleep" /><category term="domain" /><category term="impression" /><category term="spell" /><category term="Android" /><category term="Caja" /><category term="const" /><category term="subclassed" /><category term="setTimeout" /><category term="wrong" /><category term="minification" /><category term="element" /><category term="guide" /><category term="Cookie" /><category term="override" /><category term="convert" /><category term="RC4" /><category term="document" /><category term="programming" /><category term="static" /><category term="usable" /><category term="objects" /><category term="safe" /><category term="name" /><category term="single" /><category term="__wakeup" /><category term="WeakMap" /><category term="expression" /><category term="JsonML" /><category term="first" /><category term="book" /><category term="blog" /><category term="Web 2.0" /><category term="Phomet" /><category term="Liquid" /><category term="position" /><category term="cross-platform" /><category term="ECMAScript 5" /><category term="isPrototypeOf" /><category term="Callback" /><category term="mode" /><category term="Number" /><category term="implicit" /><category term="NekoVM" /><category term="handshake" /><category term="JHP" /><category term="languages" /><category term="RitaliaCamp1" /><category term="exit" /><category term="Netbook" /><category term="Rant" /><category term="fail" /><category term="snow" /><category term="data" /><category term="progress" /><category term="reader" /><title type="text">Web Reflection</title><subtitle type="html">behind the design</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://webreflection.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default?start-index=26&amp;max-results=25" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>466</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/WebReflection" /><feedburner:info uri="webreflection" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry><id>tag:blogger.com,1999:blog-34454975.post-4531196908032574178</id><published>2012-02-05T10:36:00.003+01:00</published><updated>2012-02-05T10:43:35.469+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="JS1K" /><category scheme="http://www.blogger.com/atom/ns#" term="markdown" /><title type="text">JS1K - Markdown</title><content type="html">Well, it does not look that good in the &lt;a href="http://js1k.com/2012-love/demo/1030"&gt;js1k page&lt;/a&gt;, so here the link to the &lt;a href="http://www.3site.eu/love/markdown.html"&gt;official &lt;strong&gt;demo&lt;/strong&gt; hosted by my site&lt;/a&gt;.&lt;br /&gt;Check the source code there, the page is entirely written in Markdown :)&lt;br /&gt;&lt;br /&gt;&lt;img src="http://www.3site.eu/love/markdown.png" width="380" /&gt;&lt;br /&gt;&lt;br /&gt;I submitted this demo because Markdown is widely used, and I believed loved too, by many developers and specially in github, but I may consider to create the whole thing in less than 1kb using gzip compression if people will like the idea.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-4531196908032574178?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/4531196908032574178/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=4531196908032574178" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/4531196908032574178" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/4531196908032574178" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/IlkxUKdUsbA/js1k-markdown.html" title="JS1K - Markdown" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>2</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/02/js1k-markdown.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-7187947638884101226</id><published>2012-02-03T08:11:00.013+01:00</published><updated>2012-02-04T12:34:30.662+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="hart" /><category scheme="http://www.blogger.com/atom/ns#" term="demo" /><category scheme="http://www.blogger.com/atom/ns#" term="love" /><category scheme="http://www.blogger.com/atom/ns#" term="JS1K" /><title type="text">Love ALL The Web</title><content type="html">&lt;strong&gt;update&lt;/strong&gt; no selection problems anymore ... eat the cake now&lt;br /&gt;&lt;br /&gt;Maybe 'cause San Valentine is coming, maybe 'cause &lt;a href="https://twitter.com/voodootikigod"&gt;Chris Williams&lt;/a&gt; started it, promoting an &lt;a href="http://blip.tv/jsconfeu/chris-williams-an-end-to-negativity-5635852"&gt;end to negativity&lt;/a&gt;, or maybe 'cause the web has been recently under attack ... no matter why, the topic of this &lt;a href="http://js1k.com/2012-love/"&gt;js1k&lt;/a&gt; contest is Love so here I am introducing my proposal, &lt;a href="https://twitter.com/js1k/status/165248088661966848"&gt;the very first demo&lt;/a&gt; submitted this year.&lt;br /&gt;Click the link once to see it in action through following iframe:&lt;br /&gt;&lt;br /&gt;&lt;iframe frameborder="0" width="480" height="280" src="http://www.3site.eu/love/"&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;What Is It&lt;/h3&gt;A simple script able to bring random harts behind the mouse or the finger in any page you want, even Facebook :)&lt;br /&gt;In order to do this, you can bookmark the link dragging into your bookmark bar, change the name (i.e. LOVE), and start surfing surrounded by little harts any new page you visit by simply clicking it. I know it's a silly demo, but it was a quick and interesting experiment I could recycle with any sort of different shape since the graphic is directly drawn on every little canvas.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Technical Details&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;compatible with all modern mobile and desktop browsers, included IE9&lt;/li&gt;&lt;li&gt;unobtrusive, it should not affect much the normal behavior of the generic page&lt;/li&gt;&lt;li&gt;based on &lt;a href="https://developer.mozilla.org/en/DOM/window.requestAnimationFrame"&gt;requestAnimationFrame&lt;/a&gt; where supported&lt;/li&gt;&lt;li&gt;lazy pointer evaluation, no matter if your tablet is attached to a deck with a mousepad, touch screens and other pointers are all supported at runtime&lt;/li&gt;&lt;li&gt;it fits in &lt;strike&gt;1020&lt;/strike&gt; 1023 bytes after Closure Compiler Advanced minification plus extra clean up performed by YUI Compressor (plus few manual tweaks for numbers) ... once gzipped, it fits in about 0.5Kb&lt;/li&gt;&lt;li&gt;1 hour of work, included mobile and cross browsers tests ( plus 20 minutes to think about a solution and fix the text selection problem )&lt;/li&gt;&lt;li&gt;easy to recycle, a single change in the draw function and anything you want could be displayed, even smoke effect or rainbows&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Discoveries During Creation&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;performances boost with requestAnimationFrame is unbelievable, if you compare current Opera browser VS Chrome, Safari, Webkit, or Firefox, you'll see the difference against setTimeout&lt;/li&gt;&lt;li&gt;IE9 and IE10 awesome canvas performances become crap once more than a canvas is created at runtime. If you see how slow this thing could be in my Netbook in IE compared to others, you'll rethink about how fast canvases are in MS browser: it is that fast, but only if there is one of them&lt;/li&gt;&lt;li&gt;Opera still doesn't support requestAnimationFrame even if prefixed with the little o&lt;/li&gt;&lt;li&gt;the canvas &lt;a href="https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes#arc_example"&gt;arc()&lt;/a&gt; method is completely freak, only few browsers give what you expect. Compare the bigger hart on click in Chrome and Firefox, as example, Chrome gonna show Mickey Mouse like hart&lt;/li&gt;&lt;li&gt;YUI Compressor after Google Closure Compiler Advanced is able to produce a slightly smaller output preserving functionality&lt;/li&gt;&lt;li&gt;Chrome DOM inspector is really smart. While Safari and Webkit becomes much slower during inspection, Chrome seems to use a "&lt;i&gt;requestDOMInspection&lt;/i&gt;" like mechanism to do not slow down the page during DOM changes&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Have fun with JS1K&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-7187947638884101226?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/7187947638884101226/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=7187947638884101226" title="8 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7187947638884101226" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7187947638884101226" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/PM6jycICVXM/love-all-web.html" title="Love ALL The Web" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>8</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/02/love-all-web.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-5734794714467497042</id><published>2012-01-18T01:10:00.003+01:00</published><updated>2012-01-18T01:12:30.236+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Map" /><category scheme="http://www.blogger.com/atom/ns#" term="Harmony" /><category scheme="http://www.blogger.com/atom/ns#" term="ES6" /><category scheme="http://www.blogger.com/atom/ns#" term="Set" /><category scheme="http://www.blogger.com/atom/ns#" term="WeakMap" /><category scheme="http://www.blogger.com/atom/ns#" term="Rhino" /><category scheme="http://www.blogger.com/atom/ns#" term="node.js" /><category scheme="http://www.blogger.com/atom/ns#" term="polyfills" /><category scheme="http://www.blogger.com/atom/ns#" term="browser" /><title type="text">ES6 Harmony Collections Fast Polyfill</title><content type="html">Well, just in case you read RSS and you missed my tweet ... everything you need to know in &lt;a href="https://github.com/WebReflection/es6-collections#readme"&gt;github repository&lt;/a&gt;.&lt;br /&gt;Have fun with Harmony Collections&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-5734794714467497042?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/5734794714467497042/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=5734794714467497042" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/5734794714467497042" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/5734794714467497042" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/0_G9-DIpsNs/es6-harmony-collections-fast-polyfill.html" title="ES6 Harmony Collections Fast Polyfill" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>0</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/01/es6-harmony-collections-fast-polyfill.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-150497766504525989</id><published>2012-01-16T17:51:00.010+01:00</published><updated>2012-01-16T18:33:30.945+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="EventListener" /><category scheme="http://www.blogger.com/atom/ns#" term="API" /><category scheme="http://www.blogger.com/atom/ns#" term="node.js" /><category scheme="http://www.blogger.com/atom/ns#" term="DOM" /><category scheme="http://www.blogger.com/atom/ns#" term="EventEmitter" /><title type="text">On EventEmitter In node.js</title><content type="html">Today I had a whole &lt;a href="http://nodejs.org/"&gt;node.js&lt;/a&gt; session and I have spent a bit of time looking at current EventEmitter implementation.&lt;br /&gt;I have twitted already that it sucks as it is, and while it's really trivial to implement the &lt;a href="https://github.com/WebReflection/yuno/blob/master/src/events/EventEmitter.js"&gt;same for any browser&lt;/a&gt;, I believe many mistakes have been made about the &lt;a href="http://nodejs.org/docs/latest/api/events.html"&gt;API&lt;/a&gt;. Here the list:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;&lt;strong&gt;on()&lt;/strong&gt; is a shortcut for addListener but there is &lt;strong&gt;no off()&lt;/strong&gt; as removeListener's shortcut (inconsistent)&lt;/li&gt;&lt;li&gt;&lt;strong&gt;add/removeListener&lt;/strong&gt; is not DOM friendly, we cannot reuse an EventEmitter in the browser without double checking if those methods exist&lt;/li&gt;&lt;li&gt;&lt;strong&gt;removeAllListeners()&lt;/strong&gt; accepts no arguments and cleans up the whole emitter but there is no way to retrieve all listeners via &lt;strong&gt;listeners()&lt;/strong&gt; passing no arguments (again, inconsistent)&lt;/li&gt;&lt;li&gt;there's no possibility to use &lt;strong&gt;handleEvent&lt;/strong&gt; property, as already defined in the &lt;a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener"&gt;EventListener&lt;/a&gt;, once again objects are not reusable between client and server&lt;/li&gt;&lt;li&gt;&lt;strong&gt;no duplicated checks&lt;/strong&gt; for both addListener and removeListener, this is totally inconsistent against DOM &lt;a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget"&gt;EventTarget&lt;/a&gt; plus I found it kinda hilarious since there is also a max number of listeners allowed defined via &lt;strong&gt; setMaxListeners&lt;/strong&gt; method ... if we add same listener twice, it's fired twice ... a non-sense for those coming from the web. We also need to &lt;em&gt;removeListener&lt;/em&gt; twice or more 'cause we have no idea if same listeners has been added by mistake twice so ... it's just screwed up, removing a specific listener may be not enough and there is no easy way to check if the listener has been removed or not&lt;/li&gt;&lt;li&gt;there is no interface to define events plus the single argument is not a DOM Event like, not even an object with data property and at least a type that points to the event name ... once again, not possible to reuse anything on DOM world&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Why All Of This Is Bad&lt;/h3&gt;node.js is bringing a lot of non JavaScripters and non browser friendly JS developers into its community and this is the good part. What is absolutely bad is that if node.js won't be minimally aligned with the rest of the code in the browsers out there our life as "&lt;i&gt;one language everywhere&lt;/i&gt;" will become harder than ever.&lt;br /&gt;I have personally created &lt;a href="https://github.com/WebReflection/wru"&gt;wru&lt;/a&gt; which runs in all browsers and many server side JS environments but what I would like to avoid is to write twice any sort of test because of weirdly implemented APIs.&lt;br /&gt;If it's about shortcutting, as example, &lt;em&gt;on()&lt;/em&gt; and &lt;em&gt;off()&lt;/em&gt; are more than welcome but why on earth the long version should be &lt;em&gt;addListener&lt;/em&gt; rather than &lt;em&gt;addEventListener&lt;/em&gt;?&lt;br /&gt;Why events passed as objects since ever in client JS should be passed as string with optional extra data as second argument?&lt;br /&gt;Where are defaults control over events fired across more listeners?&lt;br /&gt;Why on earth &lt;em&gt;handleEvent&lt;/em&gt; is not supported and a listener can be only a function which most likely will require a bind to something else?&lt;br /&gt;Why is it possible to erase all listeners without even knowing "who set them where" but it's not possible to retrieve all of them so that at least we could act accordingly with the event name following some rule rather than "&lt;i&gt;just remove them all&lt;/i&gt;" ?&lt;br /&gt;&lt;br /&gt;I hope somebody will agree with me, considering flakey points I have already described and changing or improving ASAP this EventEmitter API ... it would be sooooooo coooool to be aligned in both worlds for at least the most used pattern/procedure ever in JS world, don't you say? Thanks for your attention.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-150497766504525989?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/150497766504525989/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=150497766504525989" title="7 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/150497766504525989" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/150497766504525989" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/-a-h0yTgVTA/on-eventemitter-in-nodejs.html" title="On EventEmitter In node.js" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>7</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/01/on-eventemitter-in-nodejs.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-1441988846510145281</id><published>2012-01-15T16:40:00.006+01:00</published><updated>2012-01-15T19:11:33.863+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="yuno" /><category scheme="http://www.blogger.com/atom/ns#" term="loader" /><category scheme="http://www.blogger.com/atom/ns#" term="CommonJS" /><category scheme="http://www.blogger.com/atom/ns#" term="require" /><category scheme="http://www.blogger.com/atom/ns#" term="pattern" /><category scheme="http://www.blogger.com/atom/ns#" term="AMD" /><category scheme="http://www.blogger.com/atom/ns#" term="module" /><category scheme="http://www.blogger.com/atom/ns#" term="browser" /><title type="text">Y U NO use libraries and add stuff</title><content type="html">This is an early introduction to a project I have been thinking about for a while.&lt;br /&gt;The project is &lt;a href="https://github.com/WebReflection/yuno"&gt;already usable in github&lt;/a&gt; but the documentation is lacking all over the place so please be patient and I'll add everything necessary to understand and use &lt;strong&gt;yuno&lt;/strong&gt;.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Zero Stress Namespace And Dependencies Resolver&lt;/h3&gt;Let's face the reality: today there is still no standard way to include dependencies in a script.&lt;br /&gt;If we are using a generic JS loader, the aim is to simply download files and eventually wait for one or more dependency in order to be able to use everything we need.&lt;br /&gt;The &lt;strong&gt;require&lt;/strong&gt; logic introduced via &lt;em&gt;node.js&lt;/em&gt; does not scale in the browser due synchronous nature of the method itself plus the sandbox not that easy to emulate in a browser environment.&lt;br /&gt;The &lt;strong&gt;AMD&lt;/strong&gt; concept is kinda &lt;i&gt;OKish&lt;/i&gt; but once we load after dependencies, there is no way to implement a new one within the callback unless we are not exporting.&lt;br /&gt;I find AMD approach surely the most convenient but still not the best one:&lt;ol&gt;&lt;li&gt;we cannot implement a &lt;em&gt;provide&lt;/em&gt; like procedure, whenever this could be handy or not&lt;/li&gt;&lt;li&gt;it's not clear within the module code itself, what we are exporting exactly&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Specially the last point means that AMD does not scale properly with already combined code because AMD relies in the module/folder structure itself ... so, cannot we do anything better than what we have so far?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The yuno Concept&lt;/h3&gt;&lt;img src="http://s3.amazonaws.com/ragefaces/fd910848b62298e03671f2e200c4c245.png" width="400" /&gt;&lt;br /&gt;Directly out of a well known meme, &lt;strong&gt;yuno&lt;/strong&gt; logic is quite straightforward:&lt;ul&gt;&lt;li&gt;automagically resolved path, you point once to &lt;em&gt;yuno.js&lt;/em&gt; file in your page and you are ready to go&lt;/li&gt;&lt;li&gt;compatible with already combined files (smart builder coming soon)&lt;/li&gt;&lt;li&gt;&lt;strong&gt;yuno.use()&lt;/strong&gt; semantic method to define dependencies, if necessary&lt;/li&gt;&lt;li&gt;&lt;strong&gt;yuno.use().and()&lt;/strong&gt; resolved callback to receive modules AMD style once everything has been loaded&lt;/li&gt;&lt;li&gt;&lt;strong&gt;yuno.add()&lt;/strong&gt; standard ES5 way to define new namespaces, objects, properties, or constructors ( so no extra note in the documentation is needed )&lt;/li&gt;&lt;li&gt;cross referenced dependencies automagically resolved: if two different scripts needs same library, this will be loaded once for both&lt;/li&gt;&lt;li&gt;external url compatible, because you may want to include a file from some known CDN rather than put all scripts in your own host ( speed up common libraries download across different libraries that depend on same core, e.g/ jQuery )&lt;/li&gt;&lt;li&gt;modules, namespaces, or global objects, cannot be reassigned twice, which means if we are adding twice same thing we are doing it wrong, but if we are not aware of other script that added same thing before we have a notification&lt;/li&gt;&lt;li&gt;something else I may decide to add after this post&lt;/li&gt;&lt;/ul&gt;Here some example:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// define a jQuery plugin&lt;br /&gt;yuno.use(&lt;br /&gt;  "jQuery",&lt;br /&gt;  "extraStuff"&lt;br /&gt;).and(function (jQuery, extraStuff) {&lt;br /&gt;  yuno.add(jQuery.fn, "myPlugin", {value:function () {&lt;br /&gt;    // your amazing code here&lt;br /&gt;  }});&lt;br /&gt;  // we may opt for just this line&lt;br /&gt;  jQuery.fn.myPlugin = function () {};&lt;br /&gt;  // in order to export our plugin&lt;br /&gt;  // however, the purpose of yuno is to have&lt;br /&gt;  // a common recognizable way to understand&lt;br /&gt;  // what the module is about&lt;br /&gt;  // plus the "add" method is safer&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Let's imagine that &lt;i&gt;extraStuff&lt;/i&gt; contains similar code:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// define extraStuff&lt;br /&gt;yuno.use(&lt;br /&gt;  "jQuery"&lt;br /&gt;).and(function (jQuery) {&lt;br /&gt;  yuno.add(jQuery.fn, "extraStuff", {value:function () {&lt;br /&gt;    // your amazing code here&lt;br /&gt;  }});&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Both plugin and extraStuff needs jQuery to be executed ... will jQuery be loaded twice? Nope, it's simply part of a queue of modules that needs to be resolved.&lt;br /&gt;As soon as it's loaded/added once, every module that depends on jQuery will be notified so that if the list of dependencies is fully loaded, the callback passed to &lt;em&gt;and&lt;/em&gt; will be executed.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Y U NO Add&lt;/h3&gt;Modules are only one part of the proposal since we may define a script where no external dependency is needed.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// note: no external dependency, just add&lt;br /&gt;yuno.add(this, "MyFreakingCoolConstructor", {value:&lt;br /&gt;  function MyFreakingCoolConstructor() {&lt;br /&gt;    // freaking cool stuff here&lt;br /&gt;  }&lt;br /&gt;});&lt;br /&gt;// this points to the global object so that ...&lt;br /&gt;MyFreakingCoolConstructor.prototype.doStuff = function () {&lt;br /&gt;  // freaking cool method&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The &lt;em&gt;yuno.add&lt;/em&gt; method reflects &lt;em&gt;Object.defineProperty&lt;/em&gt; which means for ES5 compatible browsers getters, setters, and values, are all accepted and flagged as not enumerable, not writable, and not configurable by default.&lt;br /&gt;Of course we can re-define this behavior but most likely this is what we need/want as default in any case ... isn't it?&lt;br /&gt;For those browsers not there yet, the &lt;em&gt;Object.defineProperty&lt;/em&gt; method is partially shimmed where &lt;em&gt;__defineGetter/Setter__&lt;/em&gt; or simply the value property will be used instead.&lt;br /&gt;Bear in mind this shim may change accordingly with real needs but so far all mobile browsers should work as expected plus all Desktop browsers except IE less than 9 ... not so common targets for modern web sites.&lt;br /&gt;Last, but not least, &lt;em&gt;yuno&lt;/em&gt; logic does not necessarily need the &lt;em&gt;add&lt;/em&gt; call so feel free to simply define your global object or your namespace the way you want.&lt;br /&gt;However, as I have said before, the &lt;em&gt;add&lt;/em&gt; method is a simple call able to make things more robust, to speedup and ensure notifications, and to use a standard, recognizable pattern, to define our own objects/functions being sure nobody did before thanks to defaults descriptor behavior which is not writable and not configurable indeed.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;To DOs&lt;/h3&gt;This is just an initial idea of what the &lt;em&gt;yuno&lt;/em&gt; object is able to do but few things are in my mind. On top of the list we have the possibility to shortener CDN calls via prefixes such &lt;em&gt;"cdn:jQuery"&lt;/em&gt;, as example, in order to use most common CDNs to load widely shared libraries.&lt;br /&gt;Last, but not least, the reason I am writing this is because I am personally not that happy with any solution we have out there so if you are willing to contribute, please just leave a comment, thanks.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-1441988846510145281?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/1441988846510145281/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=1441988846510145281" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/1441988846510145281" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/1441988846510145281" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/LlMO_ZKqNvo/y-u-no-use-libraries-and-add-stuff.html" title="Y U NO use libraries and add stuff" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>5</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/01/y-u-no-use-libraries-and-add-stuff.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-4319750001280541566</id><published>2012-01-10T00:29:00.004+01:00</published><updated>2012-01-10T13:57:51.679+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="DOM" /><category scheme="http://www.blogger.com/atom/ns#" term="bind" /><category scheme="http://www.blogger.com/atom/ns#" term="events" /><category scheme="http://www.blogger.com/atom/ns#" term="proposal" /><title type="text">Introducing ObjectHandler</title><content type="html">since the discussion about a better Function#bind will probably never end, and since a must have dependency would be the ES6 WeakMap which is in any existent shim leak prone due lack of control via ES5+, I have proposed another way to solve the problem.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;ObjectHandler IDL Like&lt;/h3&gt;&lt;pre class="code"&gt;&lt;br /&gt;/**&lt;br /&gt; *  interface ObjectHandler implements EventListener {&lt;br /&gt; *      void                handleEvent(in Event evt);&lt;br /&gt; *      void                remitEvent(in Event evt);&lt;br /&gt; *      attribute   Object  events;&lt;br /&gt; *  };&lt;br /&gt; *&lt;br /&gt; *  @link   http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener&lt;br /&gt; */&lt;br /&gt;var ObjectHandler = {&lt;br /&gt;  handleEvent: function handleEvent(e) {&lt;br /&gt;    var&lt;br /&gt;      events = this.events,&lt;br /&gt;      type = e.type&lt;br /&gt;    ;&lt;br /&gt;    if (events.hasOwnProperty(type)) {&lt;br /&gt;      events[type].call(this, e);&lt;br /&gt;    }&lt;br /&gt;  },&lt;br /&gt;  // it could be called removeEvent too, as you wish&lt;br /&gt;  remitEvent: function cancelEvent(e) {&lt;br /&gt;    e.currentTarget.removeEventListener(&lt;br /&gt;      e.type, this, e.eventPhase === e.CAPTURING_PHASE&lt;br /&gt;    );&lt;br /&gt;  }&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Above object is an Abstract implementation. In JavaScript we can borrow methods so whatever "class" would like to implement above behavior should extend the object or borrow those two methods and specify an &lt;strong&gt;events&lt;/strong&gt; property.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Examples&lt;/h3&gt;Let's say we have a UI Class which aim is to react to certain events ... let's call it button:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;function UIButton(parentNode) {&lt;br /&gt;  // add the node&lt;br /&gt;  this.el = parentNode.appendChild(&lt;br /&gt;    parentNode.ownerDocument.createElement("button")&lt;br /&gt;  );&lt;br /&gt;  // add quickly events to the node&lt;br /&gt;  for (var key in this.events) {&lt;br /&gt;    // add the listener ... &lt;br /&gt;    // NOTE: nothing to bind, no duplicated entries either&lt;br /&gt;    this.el.addEventListener(key, this, false);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// extends the class&lt;br /&gt;Object.defineProperties(&lt;br /&gt;  UIButton.prototype,&lt;br /&gt;  {&lt;br /&gt;    // implements ObjectHandler&lt;br /&gt;    handleEvent: {value: ObjectHandler.handleEvent},&lt;br /&gt;    remitEvent: {value: ObjectHandler.remitEvent},&lt;br /&gt;    events: {value: {&lt;br /&gt;      // only once thanks to remitEvent&lt;br /&gt;      click: function (evt) {&lt;br /&gt;        alert("only once");&lt;br /&gt;        this.remitEvent(evt);&lt;br /&gt;      },&lt;br /&gt;      // some decoration on actions&lt;br /&gt;      mousedown: function (evt) {&lt;br /&gt;        this.el.style.border = "1px solid black";&lt;br /&gt;      },&lt;br /&gt;      mouseup: function (evt) {&lt;br /&gt;        this.el.style.border = null;&lt;br /&gt;      },&lt;br /&gt;      // recicle mouseup behavior&lt;br /&gt;      mouseout: function (evt) {&lt;br /&gt;        this.events.mouseup.call(this, evt);&lt;br /&gt;      }&lt;br /&gt;    }}&lt;br /&gt;  }&lt;br /&gt;);&lt;br /&gt;&lt;br /&gt;// example on window load&lt;br /&gt;this.onload = function () {&lt;br /&gt;  new UIButton(document.body);&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Got it? Events property is simply an object shared through the prototype with properties name that are exactly the equivalent of DOM events name ... easy!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Pros&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;memory safe, nothing to bind, trap as bound, and stuff like this ... all instances will share same logic and bind is not even needed, aka: problem solved&lt;/li&gt;&lt;li&gt;events are defined in a single place, easy to find, maintain, extend&lt;/li&gt;&lt;li&gt;events are recycled, as it was as example for mouseout, though the instance&lt;/li&gt;&lt;li&gt;most UI frameworks need the instance rather than the DOM node, to behave accordingly&lt;/li&gt;&lt;li&gt;ObjectHandler can be used same way for "ObjectTarget", those listeners/able JS implementations, in order to uniform an event driven approach&lt;/li&gt;&lt;li&gt;no risk to bind twice, no risk to remove the wrong callback, bound or not, it's the instance that makes the deal, not inline functions so it's less error prone&lt;/li&gt;&lt;li&gt;&lt;strong&gt;performances&lt;/strong&gt; in therms of both memory footprint and operation per each instance ... once again, no need to bind all methods to the instance itself ... what is in events is basically bound automatically through a single entry point, defined in ObjectHandler, for every single use case&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Cons&lt;/h3&gt; ... no idea, I cannot find any and I just like this solution over the Function#bind improvements since it's both cross platform, whenever addEventListener is present, but it can be recycled for any other no DOM use case as long as the event will have a currentTarget property that points to the current instance ( I will write an example/proposal soon ... OK? )&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;The main problem with proposal is adoptions and I would like to know UI Framework users feedbacks. Ideally this way to handle events could become a de facto standard dropping the redundant and massive usage of Function#bind for cases where the focus should be for the instance and not for the callback.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-4319750001280541566?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/4319750001280541566/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=4319750001280541566" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/4319750001280541566" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/4319750001280541566" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/ppjXnKYMzTM/introducing-objecthandler.html" title="Introducing ObjectHandler" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>3</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/01/introducing-objecthandler.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-6460446763109846399</id><published>2012-01-04T23:09:00.014+01:00</published><updated>2012-01-05T17:55:04.349+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="function" /><category scheme="http://www.blogger.com/atom/ns#" term="improvement" /><category scheme="http://www.blogger.com/atom/ns#" term="bind" /><title type="text">Improving Function.prototype.bind</title><content type="html">There are a couple of things I have never liked that much about &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind"&gt;Function#bind&lt;/a&gt; and this post is about proposing a pattern hopefully better than common one.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;At The End Of The Function&lt;/h3&gt;A common argument about parentheses around inline invoked functions is that developers can easily recognize them.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// considered ambiguous&lt;br /&gt;var someThing = function () {&lt;br /&gt;  return {};&lt;br /&gt;}();&lt;br /&gt;&lt;br /&gt;// considered not ambiguous&lt;br /&gt;var someThing = (function () { // note the parenthesis&lt;br /&gt;  return {};&lt;br /&gt;}()); // note the parenthesis&lt;br /&gt;&lt;br /&gt;// exact same behavior of latest one&lt;br /&gt;// but considered slightly ambiguous&lt;br /&gt;var someThing = (function () { // note the parenthesis&lt;br /&gt;  return {};&lt;br /&gt;})(); // note the parenthesis&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The parentheses version apparently wins but, specially when no assignment is needed, I believe these are even less ambiguous:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;-function(){&lt;br /&gt;  alert("OK");&lt;br /&gt;}();&lt;br /&gt;&lt;br /&gt;+function(){&lt;br /&gt;  alert("OK");&lt;br /&gt;}();&lt;br /&gt;&lt;br /&gt;!function(){&lt;br /&gt;  alert("OK");&lt;br /&gt;}();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Of course if there is an operator that function will be executed, why on earth anyone would do that otherwise?&lt;br /&gt;Anyway, the problem with all of these human friendly syntax pattern recognition strategies, is that the context of the function, or the whole code behavior, could be polluted/changed via &lt;em&gt;bind&lt;/em&gt; or &lt;em&gt;call&lt;/em&gt; or &lt;em&gt;apply&lt;/em&gt; so we need in any case to scroll 'till the end to better understand what is going on inside the function and what is returned, exactly.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// ES3 example&lt;br /&gt;var something = (function(){&lt;br /&gt;   // this could be global object or something else&lt;br /&gt;   return this.doSomeStuff();&lt;br /&gt;}.bind(unexpectedObject)); // or call for other cases&lt;br /&gt;&lt;br /&gt;// ES5&lt;br /&gt;var something = (function(){"use strict";&lt;br /&gt;   // if there is a this reference&lt;br /&gt;   // we need to reach the end to understand&lt;br /&gt;   // what is it&lt;br /&gt;   return this.doSomeStuff();&lt;br /&gt;}.bind(unexpectedObject));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The summary is that &lt;em&gt;bind&lt;/em&gt;, used inline, is more like a &lt;a href="http://united-coders.com/christian-harms/what-are-yoda-conditions"&gt;yoda condition&lt;/a&gt; rather than a developer friendly helper so the first point is that &lt;em&gt;bind&lt;/em&gt;, as it is, forces the developer to always check the end of the function to know if this has been executed inline or it has been bound to a different context, as well as yoda conditions forces the developer to read "&lt;i&gt;upside down&lt;/i&gt;" a statement.&lt;br /&gt;Last, but not least, of course if it's just about bind, parentheses are not helping at all ... still scroll 'till the end&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// perfectly valid, not even executed&lt;br /&gt;// but still important to know&lt;br /&gt;// what will be the context for future calls&lt;br /&gt;var something = function(){&lt;br /&gt;   return this.doSomeStuff();&lt;br /&gt;}.bind(unexpectedObject);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Team Speaking&lt;/h3&gt;Ok, agreed, a function bigger than 10 lines is not that good and should be split and &lt;i&gt;blah blah blah&lt;/i&gt; ... point is that sometimes function have to be big since these provide us a way to create private variables and methods ... ok?&lt;br /&gt;Also if that was "&lt;i&gt;the good part&lt;/i&gt;", I mean just putting parentheses around, there is some conflict with the fact that functions should not be that long ... I mean, how can we mistake whatever happened in 10 lines?&lt;br /&gt;The truly good part could be done by developers, specially those that work in a team.&lt;br /&gt;The first good rule is to write a bloody single line comment at the very first line, this would just solve everything:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var something = function () {&lt;br /&gt;  //! executed inline, returns object&lt;br /&gt;&lt;br /&gt;  ... the rest of the code ...&lt;br /&gt;}();&lt;br /&gt;&lt;br /&gt;var somethingElse = function () {&lt;br /&gt;  //! bound to variable obj&lt;br /&gt;&lt;br /&gt;  ... the rest of the code ...&lt;br /&gt;}.bind(obj);&lt;br /&gt;&lt;br /&gt;var somethingCrazy = function () {&lt;br /&gt;  //! bound to obj + executed inline&lt;br /&gt;&lt;br /&gt;  .. the rest of the code ...&lt;br /&gt;}.bind(obj)();&lt;br /&gt;&lt;br /&gt;-function(){&lt;br /&gt;  // bound to obj&lt;br /&gt;}.bind(obj)();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Got it? Nobody would ever complain about these little helps ... isn't it? But since we are all lazy devs, the second helper is function declaration rather than function expression.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;function impossibruToConfuse(){}&lt;br /&gt;&lt;br /&gt;var something = impossibruToConfuse.bind(obj);&lt;br /&gt;var something = impossibruToConfuse();&lt;br /&gt;var something = impossibruToConfuse.call(obj);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;With a single line to read I believe the problem is solved ... isn't it? Still ways to improve.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Unable To Retrieve Same Bound Function&lt;/h3&gt;The second most annoying thing ever, something that leads inevitably to uncomfortable patterns, is the inability to retrieve an already bound function through the same object.&lt;br /&gt;In my humble opinion, was a freaking design mistake indeed to create a new bound object per each bind call since I believe nobody in this world ever used this "&lt;i&gt;feature&lt;/i&gt;".&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;function task(){}&lt;br /&gt;&lt;br /&gt;// Y U NO THE SAME !!!&lt;br /&gt;task.bind(window) === task.bind(window);&lt;br /&gt;// false .... &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;If the function is the same it means it has same context, inner and outer scope of the other function bound to the same object.&lt;br /&gt;If we bind twice the same object we are doing it wrong 'cause most likely we never meant/need two different bound callbacks/objects for that task ... isn't it?&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;An Error Prone Logic&lt;/h4&gt;The most basic fail of this logic is about listeners, both DOM listeners or self implemented listeners, extremely common in an always more asynchronous driven language as JavaScript is.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;generic.addEventListener("stuff", stuff.bind(obj), false);&lt;br /&gt;&lt;br /&gt;// how many times have you seen this later on?&lt;br /&gt;generic.removeEventListener("stuff", stuff.bind(obj), false);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Above example won't work as expected ... of course it won't work as expected ... developers expect the same function/object, instead they have a new one.&lt;br /&gt;This approach forces developers to store temporarily the bloody bound function to some private, global, variable or property.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;obj._boundStuff = stuff.bind(obj);&lt;br /&gt;generic.addEventListener("stuff", obj._boundStuff, false);&lt;br /&gt;&lt;br /&gt;// ... later on ...&lt;br /&gt;if (obj._boundStuff) {&lt;br /&gt;  generic.removeEventListener("stuff", obj._boundStuff, false);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Remember how lazy we are so that parentheses became one of the good parts of JavaScript since a line of comment was too boring? Now look again at latest example and think how many times you have done something similar ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A Clever Object.prototype.boundTo&lt;/h3&gt;With ES5 we are so lucky to be able to pollute global constructors without influencing for/in and as long as our implementation is not obtrusive and, most important, makes sense.&lt;br /&gt;I came up with this proposal in order to solve at least latest problems described before: a &lt;strong&gt;lazy boundTo method&lt;/strong&gt;&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;!function (Object) {&lt;br /&gt;&lt;br /&gt;  // (C) WebReflection - Mit Style License&lt;br /&gt;&lt;br /&gt;  var // private scope shortcuts&lt;br /&gt;    BOUND_TO = "boundTo", // or maybe "asContextOf" ?&lt;br /&gt;    defineProperty = Object.defineProperty,&lt;br /&gt;    bind = defineProperty.bind || function (self) {&lt;br /&gt;      // simple partial shim for "not there yet" ES5 browsers&lt;br /&gt;      var callback = this;&lt;br /&gt;      return function bound() {&lt;br /&gt;        return callback.apply(self, arguments);&lt;br /&gt;      };&lt;br /&gt;    }&lt;br /&gt;  ;&lt;br /&gt;&lt;br /&gt;  defineProperty(&lt;br /&gt;    Object.prototype,&lt;br /&gt;    BOUND_TO, {&lt;br /&gt;      value: function (callback, remove) {&lt;br /&gt;        // only the very first time&lt;br /&gt;        // two private stacks are created&lt;br /&gt;        // and related to the current object&lt;br /&gt;        var&lt;br /&gt;          cbStack = [],&lt;br /&gt;          boundStack = [],&lt;br /&gt;          self = this&lt;br /&gt;        ;&lt;br /&gt;        // overwrite the inherited BOUND_TO method&lt;br /&gt;        // with the one we actually need&lt;br /&gt;        defineProperty(&lt;br /&gt;          self,&lt;br /&gt;          BOUND_TO, {&lt;br /&gt;            value: function boundTo(callback, remove) {&lt;br /&gt;              var&lt;br /&gt;                i = cbStack.indexOf(callback),&lt;br /&gt;                callback = i &lt; 0 ?&lt;br /&gt;                  boundStack[&lt;br /&gt;                    i = cbStack.push(callback) - 1&lt;br /&gt;                  ] = bind.call(callback, self)&lt;br /&gt;                  :&lt;br /&gt;                  boundStack[i]&lt;br /&gt;              ;&lt;br /&gt;              // falsy values accepted&lt;br /&gt;              // except null or undefined&lt;br /&gt;              // so it's true by default&lt;br /&gt;              if (remove == false) {&lt;br /&gt;                cbStack.splice(i, 1);&lt;br /&gt;                boundStack.splice(i, 1);&lt;br /&gt;              }&lt;br /&gt;              // returns bound callback in any case&lt;br /&gt;              // handy to remove listeners and clean stacks&lt;br /&gt;              // in one single operation&lt;br /&gt;              return callback;&lt;br /&gt;            }&lt;br /&gt;          }&lt;br /&gt;        );&lt;br /&gt;        // only the first time, invoe the overwritten method&lt;br /&gt;        // use directly latter one every other time&lt;br /&gt;        return self[BOUND_TO](callback, remove);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  );&lt;br /&gt;}(Object);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;How above snippet is supposed to be used? Here a basic example:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;generic.addEventListener("stuff", obj.boundTo(stuff), false);&lt;br /&gt;&lt;br /&gt;// ... later on ...&lt;br /&gt;generic.removeEventListener("stuff", obj.boundTo(stuff, 0), false);&lt;br /&gt;&lt;br /&gt;// bear in mind that ...&lt;br /&gt;obj.boundTo(stuff) === obj.boundTo(stuff);&lt;br /&gt;// always ... unless we release explicitly the bound function/object&lt;br /&gt;obj.boundTo(stuff, false) !== obj.boundTo(stuff);&lt;br /&gt;// since once removed, the new obj.boundTo call will create a new one&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h4&gt;Pros&lt;/h4&gt;No need to check, no need to store the bound version, memory leaks safe, no need to do anything extra except calling the method through, and this is needed, the same function.&lt;br /&gt;The semantic is straight forward and rather than a yoda condition we have a clear operation that means: return the function created to bind this object as context.&lt;br /&gt;Last, but not least, even if the function was not bound, everything should work as expected, as long as the &lt;em&gt;removeListener&lt;/em&gt; generic method has been implemented properly ( checking if the callback/object was attached already )&lt;br /&gt;&lt;h4&gt;Cons&lt;/h4&gt;Not really, but the function has to be the same. It must be said that two apparently identical functions could be just a copy and paste in two completely different outer scopes. This means that there is no bullet proof way to understand if a function written twice is similar to another one since it is not possible to understand surrounding scopes and it would be silly to do this even on the JS engine level. I am talking about another, unfortunately, common mistake:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// wrong examples ... does not work as expected&lt;br /&gt;&lt;br /&gt;generic.addListener("whatever", function () {&lt;br /&gt;  return this.whatever;&lt;br /&gt;}.bind(object), false);&lt;br /&gt;&lt;br /&gt;// followed by ...&lt;br /&gt;generic.removeListener("whatever", function () {&lt;br /&gt;  return this.whatever;&lt;br /&gt;}.bind(object), false);&lt;br /&gt;&lt;br /&gt;// or in this proposal case ...&lt;br /&gt;&lt;br /&gt;generic.addListener("whatever", object.boundTo(function () {&lt;br /&gt;  return this.whatever;&lt;br /&gt;}), false);&lt;br /&gt;&lt;br /&gt;// followed by ...&lt;br /&gt;generic.removeListener("whatever", object.boundTo(function () {&lt;br /&gt;  return this.whatever;&lt;br /&gt;}), false);&lt;br /&gt;&lt;br /&gt;// ... but this is not how JavaScript works ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Memory speaking, the very first time we use this strategy we create two extra arrays able to speed up operations through indexed function and and bound version per each object. This is inevitable in any case and it's almost exactly the same we do when we address once the bound function.&lt;br /&gt;Once the object has been Garbage Collected, related private arrays will have a reference count equal to zero so the memory should clean up automatically without problems and including all functions bound to that object.&lt;br /&gt;&lt;br /&gt;As explained in the example, it is possible in any case to release explicitly bound functions so we can feel like the memory usage is under control.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Why No Arguments&lt;/h3&gt;The combination of arguments could be such big number that this technique won't be interesting anymore, specially regarding performances.&lt;br /&gt;It does not really make sense to over complicate such basic, most needed, scenario but if you think this is the biggest impediment, then the name should simply be &lt;em&gt;asContextOf&lt;/em&gt; so that no ambiguity would be shared with &lt;em&gt;bind&lt;/em&gt; native signature.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Update - Preserving Private Methods&lt;/h3&gt;Another reason to chose my proposal is the ability to bind proper private methods without using the current instance to store the bound method anywhere ... follow &lt;a href="https://mail.mozilla.org/pipermail/es-discuss/2012-January/019277.html"&gt;the es-discuss ML&lt;/a&gt; to know more but here the stupid, basic, proof of concept:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// stupid useless example ... just as concept&lt;br /&gt;var Counter = (function () {&lt;br /&gt;  // private&lt;br /&gt;  function increase() {&lt;br /&gt;    this.clicks++;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  function Counter() {&lt;br /&gt;    // none out there should be able to retrieve the bound function&lt;br /&gt;    document.addEventListener("click", this.boundTo(increase), false);&lt;br /&gt;  };&lt;br /&gt;  Counter.prototype.clicks = 0;&lt;br /&gt;  Counter.prototype.destroy = function () {&lt;br /&gt;    // so that only this class scope can control things and nobody else&lt;br /&gt;    document.removeEventListener("click", this.boundTo(increase), false);&lt;br /&gt;  };&lt;br /&gt;  return Counter;&lt;br /&gt;}());&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;I am pretty sure this simple lazy created proposal would be ideal for many frameworks and projects but if I am missing something or if you have any improvement to suggest, I will be more than happy to listen to you.&lt;br /&gt;Enjoy simplicity over semantic, this is yet another KISS and YAGNI proposal from this blog.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-6460446763109846399?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/6460446763109846399/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=6460446763109846399" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/6460446763109846399" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/6460446763109846399" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/5EftFhbtpwo/improving-functionprototypebind.html" title="Improving Function.prototype.bind" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>6</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2012/01/improving-functionprototypebind.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-8892808504319268322</id><published>2011-12-30T14:26:00.011+01:00</published><updated>2012-01-02T10:51:28.679+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="CSS3" /><category scheme="http://www.blogger.com/atom/ns#" term="2011" /><category scheme="http://www.blogger.com/atom/ns#" term="html5" /><title type="text">Learning From 2011</title><content type="html">It's time to summarize at least few mistakes or epic fails of the year, hoping the next one will try to follow a better direction.&lt;br /&gt;I won't mention anything related to war, politic, Berlusconi, or fashion related stuff, other more prepared than me will do via pictures or posts, all I gonna talk about is the field I am concerned about: web and mobile web oriented technologies and facts.&lt;br /&gt;The order is completely random, so grab a mug of coffee, take few minutes, and read 'till the end, forgetting for once &lt;em&gt;tl;dr&lt;/em&gt; philosophy ;)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Partially (Multi)? Touch Device Case&lt;/h3&gt;This has been the most annoying fact of the year: vendors going out with freaking powerful mobile devices with touch or multi touch capable screen/hardware &lt;strong&gt;not exposed through the browser&lt;/strong&gt; and only available for native apps.&lt;br /&gt;We are not talking about potentially "dangerous" technologies as WebGL could be, we are talking about the most basic thing able to break 140% the user experience.&lt;br /&gt;If a user plays a native game or use a native map, as classic Map application could be, she will naturally use at least a finger, or more, to interact with the screen. Interaction does not mean &lt;em&gt;scroll the page&lt;/em&gt; and nothing else, interaction means full control of what the user is doing with the screen.&lt;br /&gt;As soon as the user surf the web, the browser pretends to know what the user would like to do on the screen without giving web developers any control over those actions.&lt;br /&gt;The inconsistent behavior comes when the &lt;strong&gt;viewport&lt;/strong&gt; meta tag is used to block, as example, the zooming in and out gesture because the whole layout has been developed for a &lt;strong&gt;static viewport&lt;/strong&gt; that should not change.&lt;br /&gt;In this case, only few vendors ( Apple ) or browsers ( Opera Mobile ) got it right, any other vendor with a WebKit based browser got it wrong. Here a few examples:&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;IE9 Mobile Epic Fail&lt;/h4&gt;IE9 is a great browser, compared with all other previous version, and it's freaking fast. This is true for both desktop and mobile phones but in latter case, IE9 is an epic fail when it comes to User Interaction.&lt;br /&gt;There is no bloody way to intercept a user moving a finger on the screen, and standard W3C Touch Events are not supported.&lt;br /&gt;You may think: oh well, I gonna use mouse events then ... and you are wrong, these are not fired until the user release her finger so ... forget about it, no "scroll" hacks will work as expected there ... also why on earth when everybody else is disabling JS actions during scrolling, IE9 Mobile fires it all the time?&lt;br /&gt;&lt;img src="http://s3.amazonaws.com/ragefaces/3fa9aa4e19889110c01bae7601d70e25.png" width="400" /&gt;&lt;br /&gt;&lt;br /&gt;Sad part is that Microsoft is investing a lot into HTML5, but if the most basic thing as Touch Events are, is not there, no reason to have the fastest mobile Canvas implementation because no game will be interactive, and no web app can be created as desired.&lt;br /&gt;Hopefully IE10 will simply follow W3C exposing both Touch and TouchList in a meaningful way ... please don't screw this or few developers will even consider to write software for this browser, thanks.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;webOS 2 Sad Fail&lt;/h4&gt;I have upgraded few minutes ago my Pre 2 to webOS 2.4.4 ... and I was expecting more from this update. My Palm Pre 2 exposes correctly multi touches through the system, but the web browser does not expose them and this is freaking annoying. Same IE9 behavior and at least at the end of 2011 I was expecting such simple browser update able to bring my Palm to the next level: User Interaction Through The Web ... &lt;strong&gt;FAIL&lt;/strong&gt;.&lt;br /&gt;The good old native Google Maps application for webOS 2.0.X is gone. This app was working like a charm and it was exposing multi touches through the multi touches capable screen ... now I have a slower and flicking version of Bing maps that is not even able to render pinch/spread without loosing the position on the screen since everything gets stuck truly easily.&lt;br /&gt;Now, I have no idea why this happened and why somebody wasted time to do this ... it's just worse than before and the browser still does not expose multi touches ... come on guys, this phone did not deserve to die like this.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Ultra Powerful ... "broken" Androids&lt;/h4&gt;It does not matter if we have 16 cores in our expensive smart phone when developers life is made harder for no reason ... with most recent Android phones we could create any sort of web application but here again, no-f*cking-body exposes TouchList via browser except few tablets out there.&lt;br /&gt;OK, still better than nothing, as it is for IE9 Mobile, FF Mobile ( I will come back later to this one ), or webOS browser, but how comes 3rd parties browsers such Opera Mobile are able to bring TouchList and expose multi touches through the multi touches capable screen and native browsers are all lacking of this basic feature?&lt;br /&gt;You don't even want to know how we managed to bring multiple touches in android devices, all you need to know is that is basically a hack and it requires a native application wrapper and this is, in my opinion, ridiculous!&lt;br /&gt;Nowadays, all users with a friend that uses an iPhone, will consider the multi touch web app broken in its android: come on, I use two fingers in other &lt;em&gt;things&lt;/em&gt; why I cannot do the same in this web site/application?&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;FireFox Mobile Fail&lt;/h4&gt;I don't know where to start with this browser ... I mean, guys, this is not Desktop, this is a touch screen. If you decide that the user cannot even scroll a paragraph horizontally because your freaking cool settings or bookmark view has to show up instead, you should create your own device and make the phone 3 times larger: 1/3 for the actual screen, 2/3 for your things nobody expect to appear during navigation.&lt;br /&gt;About touches, at least most recent version implements touch events but performances are still too bad compared with native browsers or Opera Mobile, and the fact settings or bookmarks show up when we touch close to the edge of the screen, plus the fact AFAIK there is no way to avoid this, make this browser not suitable for full screen web games/apps based on canvas: slow and unusable ... please fix/drop this!&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Update&lt;/strong&gt;It must be said that latest FF mobile brings better canvas performances and apparently it exposes a not so fast WebGL. I dd not know this the moment I wrote this post so FF Mobile is definitively already going to the right direction.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;iOS Gesture Events VS Others&lt;/h4&gt;These are not standard and nobody should care. The moment we can rely in TouchList and multi touches exposes through this interface, the problem is solved 'cause we can implement by our self any gesture we want.&lt;br /&gt;No need to wait 'till on spread/pinch are implemted and documented, just please give us TouchList and take your time after to do things properly. TouchList has been already defined ... that's all we need so far, thanks!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Curious Case of Opera Mobile&lt;/h3&gt;Opera did weird things this year ... it switched from partial ES3 support to full ES 5.1 support ... what the hell guys, congratulations! Still there is no way to understand &lt;strong&gt;numbers&lt;/strong&gt; of this browser (again: Opera Mobile, NOT Mini) .&lt;br /&gt;Today, I can say Opera Mobile is one of the fastest and most capable browsers I have been dealing with but the lack of many CSS3 features have been &lt;em&gt;the arrow in the knee&lt;/em&gt; together with the fact Opera could have been the &lt;em&gt;Phone Gap Like&lt;/em&gt; software of the year while they focused on ... I guess something else.&lt;br /&gt;Don't give up guys, Opera Mobile is amazing and people may chose to download it as soon as most common HTML5/CSS3 things are working as expected and also you may expose freaking cool stuff without necessarily follow W3C, giving web developers the possibility to distribute applications directly through your browser as native wrapper ( and fallback to Webkit for iOS ) .&lt;br /&gt;Opera has always been pioneer, and it's time to be pioneer on mobile too because on desktop I am afraid to tell you it's hard to compete. Firefox, Chrome, and Webkit Nightly, are really advanced and I believe bigger teams, what we are missing is a &lt;strong&gt;not so fragmented browser&lt;/strong&gt; that works as expected in as many devices as possible because what I have seen with all webkit versions I have worked with this year was painful, hard, inconsistent, and WTF development oriented.&lt;br /&gt;Last, but not least, If there is not SQL Database, don't put a native useless Database function on the global scope or shims are screwed and if you don't expose SQL Database, at least expose Indexed DB or shims are screwed.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Android Whatever&lt;/h3&gt;While many developers think that Android is an Operating System, I am every day more convinced that Android is a &lt;em&gt;Super Kernel&lt;/em&gt; that has almost nothing to do with the Operating System itself.&lt;br /&gt;There are too many damn versions of Android, and even same major versions do not guarantee anything.&lt;br /&gt;Every device must be tested a part because every device, with every vendor specific &lt;em&gt;gotcha&lt;/em&gt;, software, or extra cool stuff, may behave differently. Funny enough, while I was thinking this is true for the webkit based browser only, there are many exceptions device specific that do not work as expected even natively ... oh, come on, don't call it OS!&lt;br /&gt;If we think about Windows, almost every piece of hardware is supported. Then we have the classic &lt;em&gt;crapware&lt;/em&gt; every single vendor puts by default in its own distributed piece of hardware ... fair enough, at least most basic things gonna work as expected in all of them ... right?&lt;br /&gt;With Android, the most basic free version has almost nothing. Cyanogenmod is the basic example, once you install it, you gonna scream for apps you expect to be there and it comes up you need the specific Gapp package ( Google Applications ).&lt;br /&gt;Same thing with Kindle Fire, based on the very basic version of Android so common apps available for other tablets may not work or may not be there.&lt;br /&gt;This means we can trust only a truly basic set of functionalities that are hopefully working in all distributions out there but you know, this is IT, expectations are rarely matching reality.&lt;br /&gt;The performances tuning per each device is another problem, as problematic are performances of the same app through the browser compared with those through the native layer.&lt;br /&gt;If you wrap your single touch full page canvas game into phone Gap, as example, you will realize how freaking fast it is compared with the same exact code through the browser ... why that? Security layer is off plus bound stuff is limited compared with the whole browser application ... fair enough? No it's not. The moment I realize it is possible to force HW accelerated rendering via native wrapper but it's not possible to do the same via browser I start screaming ... let us develop through the web or stop telling us you support standards because if these are limited intentionally then those not supported are developers themselves.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Mobile Web Apps Too Limited&lt;/h3&gt;I really hope I won't need to write a similar post at the end of 2012 but I am not sure there will be many progresses here ...&lt;br /&gt;W3C is slow, plus it may waste their/our time. Web SQL Database is an example, something I loved screwed by dependencies free purist.&lt;br /&gt;I have talked about Web SQL many times and right now I don't care about this specific topic, all I care is about moving forward.&lt;br /&gt;Time to agree and promote such interface to drop it after 2 years is not the way to go.&lt;br /&gt;Time to replace such interface with another one limited, slower, and not widely adopted as IndexedDB is, still not the way to go.&lt;br /&gt;We need a database, please put it there one ASAP and &lt;strong&gt;drop 50Mb per domain/tab limit&lt;/strong&gt;.&lt;br /&gt;No fools guys, if the logic behind the Web is that &lt;strong&gt;user must explicitly agree&lt;/strong&gt; give the user full control.&lt;br /&gt;If a web application requires more than 50Mb give the user the possibility to increase the database.&lt;br /&gt;All native apps do not care about how much space is used, these simply informs the user through system settings how much stored data there is. Google Earth, as example, even maps, these are heavy memory applications that do not ask every 5 megabytes if more space can be allowed ... this was another epic fail.&lt;br /&gt;Once the user accepts the fact this web application would like to use the storage, create a way to simplify the task able to verify how much data is being stored and stop asking!&lt;br /&gt;From UX perspective is like accepting an explicit file upload/manipulation and while the file is being loaded into ram asking every 200Kb if the user would like to increase the memory allocation for that file ...&lt;br /&gt;&lt;img src="http://s3.amazonaws.com/ragefaces/4019c0bb4279608433b671092446b939.png" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;What If Every Web Page Asks For Space&lt;/h4&gt;Nothing, same is for "&lt;em&gt;what if every native app takes 4 gigs of space&lt;/em&gt;" ... either space is available or it's not possible ... is that easy ... but again, with an easy to access indicator and a limit that goes far beyond 50Mb the problem should not exist. User can clean the cache, or enable more space but it must be easy, as easy should be for web apps developers to understand the available space because if the device is full already, the 50 Mb limits is pointless in any case plus there are ways to trigger memory consumption behind the scene and fill up gigs of disk space/SSD ... once again, this ask on demand every time is an epic fail, imho.&lt;br /&gt;FYI, the behavior I am talking about is in iOS, where Android asks only once if the disk access is allowed, then it silently fails after we reach the 50Mb limit.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Native VS Web App&lt;/h4&gt;Every browser is based on a native web view or similar concept, which means every browser could expose anything. I would like to be able to record user voice via web, to decode it via audio tag, to create real time video chat, to replace all native applications and to forget Android, iOS, webOS, blackberry, Symbian, MeeGo, Windows, whatever SDK ... I want to leave the SDK power to much more complicated things and I would like to be able to do most basic things via browser, all those things that the user could do with native apps, performances a part.&lt;br /&gt;The gap between native and web app should be performances and nothing else indeed ... right now is: all possible nasty access to everything on native side, things that few users are rarely aware of, and almost no access to any functionality through the browser.&lt;br /&gt;No idea if Chrome OS solved this but if it did, I am pretty sure it did with in-house solution, same Windows 8 will do, and this is annoying at least until a jDevice library will come out able to make all these private API consistent across all platforms ... as summary, why Mobile Web App development has to be so hard is a complete mystery to me: is it about your own markets? Fine, then stop selling us your browser is promoting Standard Mobile Web development because this sounds, so far, like a big lie.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Patent Oriented Development&lt;/h3&gt;When I heard that Apple patented a slide to unlock the screen I did not feel like "&lt;em&gt;they are so advanced&lt;/em&gt;" ... I rather felt like "&lt;em&gt;is anyone trying to patent my finger&lt;/em&gt;" ?&lt;br /&gt;I move horizontally my thumb since ever and nowadays I know there is a patent for that and this is bad.&lt;br /&gt;A natural movement should never be patented ... the graphic used to guide the movement could eventually be a patent but the way I do things not.&lt;br /&gt;I don't want a patent to hold a fork, I don't want a patent for the position I use to sleep in a mattress, whatever weird sofa, or a chair, I don't want to do unnatural movements to unlock a touch screen.&lt;br /&gt;What the hell is going on here ... if I use my nose to unlock my old android device I don't have to pay the patent indirectly, right?&lt;br /&gt;Is this what is patent about? Yes, it is.&lt;br /&gt;Patents are about intellectual property of whatever but the problem is that patents are expensive, are not necessarily predictable, and all these patents are doing is to block future development on top of it, unless is not the same company.&lt;br /&gt;Patents are a sort of creativity barrier because if a company invents a generic something, nobody will even try to improve that invention due basic patent behind the original.&lt;br /&gt;Example, I use my right hand to hold the phone and when I am talking with someone I put my right thumb on the right side of the phone.&lt;br /&gt;If there is a button there, it's annoying, while if I have to swipe from left to right ... well, it's still annoying.&lt;br /&gt;Will I ever implement a swiping gesture from right to left to unlock the screen because usually the way I hold the phone is with my right finger on the right side and it's more convenient to me to swipe the other way round as it is convenient for all left hand users? Nope, I don't even want to remember that thing exist, I have to create something completely new being careful that what I am doing does not touch the other patent ... cool, uh?&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Hardware Patents&lt;/h4&gt;Same concept could be applied for hardware ... was that thing perfect? Yes, I pay the patent. Was that thing not perfect? No, I have to create something new ... even if based on laser(disc), the reason we all waited so much for new standards after the CD.&lt;br /&gt;This happened with Compact Discs, and it brought us DVD first and Blu Ray after. In the meanwhile, another standard better than CDs but a bit less capable than Blu Ray died ... fair enough, we have new hardware for all these technologies but how comes in the hardware field the patent problem is not so strong as it is for the Software one?&lt;br /&gt;3D TV, all vendors are making one, as well as CD players, DVD players, and Blu Ray players ... nobody cares about patents here, at least not the way we all do when it comes to Software.&lt;br /&gt;I don't have any answer for this but I believe patents should be re-evaluated in their meaning because in the fastest field ever, as technology/software is, something that last for 10 years is too much and price to pay is too much as well as too much is the time between the patent pending and the patent applied status.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;ES6 Focus&lt;/h3&gt;I have talked about this as well ... it's about what's truly needed today, at least in the Mobile Web Development, and the JavaScript.Next focus, often completely abstract over not-so-needed topics as syntax sugar and boring classes.&lt;br /&gt;iOS5 brought massive performances boost to all Apple devices but even having the fastest and complete browser out there, Safari Mobile cannot do miracles when it comes to performances.&lt;br /&gt;The side effect of not having performances oriented techniques in JavaScript and DOM world is that average web developers are not able to create cool stuff without draining the battery or being slightly fast only with most recent mobile devices.&lt;br /&gt;The need for performances in this Mobile era should be priority number one for W3C and a possible ES 5.2 milestone, after that take even 5 years to improve syntax with all sugar you want, if necessary, at least we can push Mobile Web Development to its limit in the meanwhile while many new proposals won't bring anything interesting, as far as I can read, performances speaking.&lt;br /&gt;We can deal with the fact protected and private variables are absent or different in JS, what we cannot deal with anymore is that a proper and fast 3D API is not available, that Parallels are not available, that WebWorkers are useless when it comes to move data back and forward, that postMessage requires a window.open which require a click which is too slow but cannot be faked ontouchend or window.open won't work anymore because not explicit ... that IndexedDB does not provide native way to join data and speed up queries, that DOM manipulation is slow, that we don't control repaints and/or reflows, that binary Arrays are still slow, that Structs like classes/objects are missing, that CSS3 is bringing logic in the view with lack of control ... etc etc ... &lt;br /&gt;I don't care if Proxy are in the browser, if these are 2X slower than good old JS on mobile, you know what I mean? We need more performances now and more APIs finalized to have access to hardware layers only SDK can expose without granting any better usage than an experienced web developer.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;WebGL Partial Fail&lt;/h3&gt;First of all this is not yet a standard, regardless the effort of the kronos group, which means browsers like Internet Explorer will never adopt this ... fair enough if we can shim through Silverlight but here comes the second point: WebGL, as well as Silverlight, are not available for mobile.&lt;br /&gt;Apple exposed it for Adds only, where adds are most likely those responsible for bad Web performances, generally speaking, due massive usage of Flash or arguable usage of automations to bring canvas Adds able to slow down all netbooks and tables out there .... congratulations, I'll never get this choices ... WebGL not for developers but for designers of adds only ... can I say brilliant?&lt;br /&gt;Too few mobile devices are exposing WebGL if not none of them while basically every mobile device has a GPU compatible with Open GL 2.0 ES&lt;br /&gt;Still experimental, true, and already available mainly for Chrome browser where Webkit, as well as Firefox, could do the same or truly similar. The direction WebGL is taking is not good at all and I can't wait to see cool demonstrations able to run with all WebGL capable browsers ... so far, not many of them ... and this is bad.&lt;br /&gt;Sony enabled WebGL in its latest version of Android, still about fragmentation, so I am expecting at least every other vendor to bring WebGL in our current devices already capable ... it was a massive fail to drop it for the whole 2011, cool things may have been experimented already on devices plus typed Arrays could have been used more even for non WebGL related tasks.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;CSS3 Partial Fail&lt;/h3&gt;As mentioned before, CSS3 are becoming the most messed part of the whole Web stack, mobile and/or desktop. Examples with &lt;em&gt;counters&lt;/em&gt; to change dynamically text via &lt;em&gt;:after&lt;/em&gt; selector ... is it just me? I mean ... dafuq is that?&lt;br /&gt;Internet Explorer dropped the most misunderstood proprietary feature as &lt;em&gt;expression&lt;/em&gt; was and webkit is introducing any sort of unmanageable logic inside CSS3? ... counters? webkitTransitionEnd withou webkitTransitionStart? No way to trigger properly transitions if not without asynchronous rendering? Lots of hacks to make them work cross platform with control through JS for something written in CSS?&lt;br /&gt;CSS3 is bringing MVC in Web world without the C and if we would like to create robust behaviors/interactions/applications that make sense, programming speaking, we should forget the case where the user has no JavaScript because CSS3 is becoming indirectly strongly dependent on JavaScript for many reasons ... why not bring standard DOM method to control states via JS, rather than control partially what is supposed to happen via CSS3 only? I don't get it, I have seen cool stuff, but I have not seen cool stuff adopted cross browser and I am not seeing cool stuff easy to handle via JS and/or vice-versa.&lt;br /&gt;CSS3 needs notification into the JS world or we gonna have Photoshop like power without tools to control what we are doing.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;I have more things to say, and more I forgot but I thought a rant on 2011 was needed at least to check, in one year, what happened, what improved, and what did not change at all.&lt;br /&gt;I hope all people that are doing hard work on daily basis to promote a better web won't take anything I wrote personal and will simply consider the point of view of somebody that works with all these things on daily basis so ... it's my personal feedback, on what I think should change ASAP and specially for mobile web development.&lt;br /&gt;&lt;br /&gt;Happy New Year Everybody&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-8892808504319268322?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/8892808504319268322/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=8892808504319268322" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8892808504319268322" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8892808504319268322" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/xQcetdf75yc/learning-from-2011.html" title="Learning From 2011" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>5</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/12/learning-from-2011.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-7083090361354753298</id><published>2011-12-21T18:31:00.005+01:00</published><updated>2011-12-21T19:29:08.670+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="performances" /><category scheme="http://www.blogger.com/atom/ns#" term="coercion" /><title type="text">Coercion Performances</title><content type="html">There are cases where JS coercion may be wanted/needed/necessary, at least logically speaking.&lt;br /&gt;&lt;br /&gt;A classic case is a list of primitives, e.g. strings, or numbers, and a check we would like to perform &lt;strong&gt;without creating a new function each time&lt;/strong&gt;.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// recycled function&lt;br /&gt;function alreadyThere(value) {&lt;br /&gt;  // wanted coercion, no cast needed&lt;br /&gt;  return value == this;&lt;br /&gt;  // shitty code, logically speaking&lt;br /&gt;  // one cast per iteration&lt;br /&gt;  return value === "" + this;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var listOfNames = ["Me", "You", "Others"];&lt;br /&gt;&lt;br /&gt;// the pointless check&lt;br /&gt;listOfNames.some(&lt;br /&gt;  // the recycled callback&lt;br /&gt;  alreadyThere,&lt;br /&gt;  // the *passed as object* this&lt;br /&gt;  "You"&lt;br /&gt;); // will be true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, for above specific case anyone would use an indexOf but this is not the point.&lt;br /&gt;The point is that in some case we may want to do more complicated stuff and compare the result with &lt;em&gt;this&lt;/em&gt;&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// know if word was already in the dictionary&lt;br /&gt;function alreadyThere(value) {&lt;br /&gt;  return value.toLowerCase() == this;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// convert the check once per iteration&lt;br /&gt;listOfNames.some(&lt;br /&gt;  alreadyThere,&lt;br /&gt;  "yoU".toLowerCase()&lt;br /&gt;); // still true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;It's About Optimizations&lt;/h3&gt;The whole point is to try to perform as less runtime computations as possible.&lt;br /&gt;Following this logic, we may decide to lower-case all items in the list once, and never again, but unfortunately this will require duplicated amount of RAM used per each collection.&lt;br /&gt;The &lt;em&gt;String#toLowerCase()&lt;/em&gt; is fast enough for a not so frequent check so why bother the RAM?&lt;br /&gt;The optimization is also to avoid &lt;em&gt;this.toLowerCase()&lt;/em&gt; per each entry of the dictionary.&lt;br /&gt;The concept here is again simple, avoid duplicated entries in a generic list of chars, but things may be similar with numbers.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Performances&lt;/h3&gt;I have created a &lt;a href="http://jsperf.com/some-coercion"&gt;specific test&lt;/a&gt; able to understand performances gap between &lt;em&gt;coercion&lt;/em&gt; and &lt;em&gt;cast per iteration&lt;/em&gt;.&lt;br /&gt;Surprising Google Chrome seems to be able to optimize in core once per iteration the cast, resulting almost twice as fast as competitors.&lt;br /&gt;Specially on mobile, the &lt;strong&gt;in core coercion&lt;/strong&gt; seems to be faster, sometimes almost twice as fast as the cast per iteration is.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;JIT Oriented Development ?&lt;/h3&gt;I believe we should code logically, rather than trust JIT optimization. What I mean is that performances test are always welcome but we all know that better logic and algorithms are always winning in therms of performances and maintainability. In this specific case, specially where mobiles suffer the most, I would never suggest to do the cast per iteration: first of all because only one engine seems to be able to optimize such cast, but we don't know if a more complex object/scenario would perform that well, secondly because if I see a cast per each loop iteration I start smelling laziness all over the place ... the boxing/unboxing has always been a well known problem performances speaking, so how can a developer approve a logic similar to &lt;em&gt;(String)alwaysSameObject&lt;/em&gt; per each iteration?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;Tools such JSLint should just do their business in these cases ... coercion is wanted/needed/logical, and unless every browser will show such gap in common tasks against coercion, I will rarely promote a cast per iteration ... and you know what? I believe that gap in Chrome, is a missed optimization in Chrome itself.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-7083090361354753298?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/7083090361354753298/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=7083090361354753298" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7083090361354753298" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7083090361354753298" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/F7I__P7_wuE/coercion-performances.html" title="Coercion Performances" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>1</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/12/coercion-performances.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-3643006474638852079</id><published>2011-12-13T21:13:00.021+01:00</published><updated>2011-12-14T08:40:16.372+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ES6" /><category scheme="http://www.blogger.com/atom/ns#" term="__noSuchMethod__" /><category scheme="http://www.blogger.com/atom/ns#" term="proxy" /><title type="text">Please, Give Us Back __noSuchMethod__ !</title><content type="html">For those who don't know what &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/NoSuchMethod"&gt;__noSuchMethod__&lt;/a&gt; is here the quick summary: it was a bloody handy non-standard method able to provide a fallback whenever we invoked an object method that did not exist.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var o = {};&lt;br /&gt;o.__noSuchMethod__(function (name, args) {&lt;br /&gt;    alert(name); // "iDoNotExist"&lt;br /&gt;    alert([].slice.call(args)); // 1,2,3&lt;br /&gt;});&lt;br /&gt;o.iDoNotExist(1, 2, 3); // will produce above alerts&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A Bit Of Background&lt;/h3&gt;Well, if you are patient enough, you may consider to read this &lt;a href="https://mail.mozilla.org/pipermail/es-discuss/2010-October/011912.html"&gt;never-ending post&lt;/a&gt; in Mozilla mailing list.&lt;br /&gt;The reason that post is called &lt;strong&gt;Proxies: get+fn vs. invoke&lt;/strong&gt; is because &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy"&gt;Proxy&lt;/a&gt; supposes to be the new way to go able to bring us much more power than we probably ever need ... but hey, this is welcome, while what is not welcome, is that Proxy may not be implemented first, which means browsers vendors should have waited to remove &lt;em&gt;__noSuchMethod__&lt;/em&gt; 'cause right now we may not have a pseudo equivalent, and second, but surely not less important, , &lt;strong&gt;Proxy does not provide the same functionality&lt;/strong&gt;.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Minified Theory Against The Practice&lt;/h3&gt;The main argument from &lt;a href="https://twitter.com/BrendanEich"&gt;@BrendanEich&lt;/a&gt; is that JavaScript has properties only so that &lt;strong&gt;o.fn() is the equivalent of o.fn.apply(o)&lt;/strong&gt;.&lt;br /&gt;While this is true with any normal object, this is &lt;strong&gt;totally different with __noSuchMethod__&lt;/strong&gt;.&lt;br /&gt;The equivalent of &lt;em&gt;__noSuchMethod__&lt;/em&gt; for that operation, and behind the scene, is:&lt;ul&gt;&lt;li&gt;is there a property in &lt;em&gt;o&lt;/em&gt; or its &lt;em&gt;__proto__&lt;/em&gt; called &lt;em&gt;fn&lt;/em&gt; ?&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;yes&lt;/strong&gt;, proceed as usual as if it was &lt;em&gt;o.fn.call(o)&lt;/em&gt; and throw error if that property was not callable&lt;/li&gt;&lt;li&gt;&lt;strong&gt;no&lt;/strong&gt;, is there a &lt;em&gt;__noSuchMethod__&lt;/em&gt; callback to burn instead of throwing an error due undefined property?&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;yes&lt;/strong&gt;, perform the current operation: &lt;em&gt;nsm_callback.apply(o, arguments)&lt;/em&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;no&lt;/strong&gt;, throw an error since property was undefined and obviously not callable&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;/ul&gt;Got it? The equivalent of &lt;em&gt;o.fn()&lt;/em&gt; in an environment where &lt;em&gt;__noSuchMethod__&lt;/em&gt; was supported is potentially different from &lt;em&gt;o.fn.apply(o)&lt;/em&gt; ... I am 100% sure Brendan knows this before and better than me and this is the reason I don't really get his strongest point.&lt;br /&gt;Once again, &lt;em&gt;o.fn()&lt;/em&gt; may be the equivalent of &lt;em&gt;nsm_callback.apply(o, arguments)&lt;/em&gt; and not &lt;em&gt;o.fn.apply(o)&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Inexistent Theory Against The Practice&lt;/h3&gt;If above "reason" was not enough, I have read even worst in the same thread. I am sorry guys, but sometimes you must be realistic and understand that if a developer does, as example, this:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// de-context fn from o and invoke it&lt;br /&gt;(o.fn)();&lt;br /&gt;&lt;br /&gt;// exact equivalent of&lt;br /&gt;var fn = o.fn; // GETTER, no invokation&lt;br /&gt;// and after ...&lt;br /&gt;fn()&lt;br /&gt;// this is a problem? we have same with missing bind then ...&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;rather than this:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// invoke fn through o as default context&lt;br /&gt;o.fn();&lt;br /&gt;// can we see the difference?&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;it means that developer has much bigger problems than &lt;em&gt;__noSuchMethod__&lt;/em&gt; inexistent &lt;em&gt;ambiguity&lt;/em&gt;, that developer does not even know that &lt;em&gt;__noSuchMethod__&lt;/em&gt; exist ... &lt;strong&gt;come on&lt;/strong&gt;!&lt;br /&gt;Going on and on, another point is that &lt;em&gt;get&lt;/em&gt; should be all we need to simulate the &lt;em&gt;__noSuchMethod__&lt;/em&gt; behavior through proxies ... but &lt;strong&gt;this is completely misleading&lt;/strong&gt;!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A Getter IS A Getter&lt;/h3&gt;Is that trivial ... if we access a generic object property we are doing nothing different from invoking a getter with such object as property context.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;o.whatever;&lt;br /&gt;// look for "whatever" property name in o&lt;br /&gt;// if found returns the "whatever" associated value&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;o.whatever.call&lt;br /&gt;// nothing change, THIS IS NOT AN INVOKE&lt;br /&gt;// look for "whatever" property name in o&lt;br /&gt;// if found returns the "whatever" associated value&lt;br /&gt;// since the value was a function, the call method is usable&lt;br /&gt;// if whatever was not defined, the call method won't exist&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Nobody should ever even consider to use property accessor and expect a &lt;em&gt;__noSuchMethod__&lt;/em&gt; behavior ... that property did not exist, what kind of &lt;em&gt;method&lt;/em&gt; would you expect to look for?&lt;br /&gt;&lt;strong&gt;call is a property of the Function.prototype&lt;/strong&gt; so following the accessor/getter logic, nothing is ambiguous here.&lt;br /&gt;Accordingly, lattest example is simply an &lt;strong&gt;inexistent mistake&lt;/strong&gt; that hopefully no developer would ever do ... but you know, shit happens, then we learn, then hopefully we don't repeat same shit.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Other Programming Languages&lt;/h3&gt;When it comes to PHP, they perfectly managed to make the behavior &lt;strong&gt;not ambiguous&lt;/strong&gt; through the &lt;em&gt;&lt;a href="http://php.net/manual/en/language.oop5.overloading.php"&gt;__call&lt;/a&gt;&lt;/em&gt; magic keyword in classes definition but no, we decided that in JavaScript we cannot even think to put an &lt;em&gt;invoke&lt;/em&gt; to make the life easier and completely NOT ambiguous for all of us ... do we?&lt;br /&gt;I still cannot understand where and what is the ambiguous part if we have an explicit invoke declaration ... maybe something a bit harder to solve behind the scene for these poor JS engines? It could be ... should we all limit JS because of this? I don't think so.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Think About Libraries APIs Migrations&lt;/h3&gt;I give you the most basic example, the most used JS library with a fake &lt;em&gt;getter&lt;/em&gt; and &lt;em&gt;setter&lt;/em&gt; behavior: &lt;strong&gt;jQuery&lt;/strong&gt;.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// jQuery simulation of getters and setters behaviors&lt;br /&gt;&lt;br /&gt;// the getter&lt;br /&gt;$("body").html(); // return string with content&lt;br /&gt;&lt;br /&gt;// the setter&lt;br /&gt;$("body").html("&lt;div&gt;whatever&lt;/div&gt;");&lt;br /&gt;// set the string with content&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;If you want, specially for chainability reasons through the simulated setter, the fact &lt;em&gt;html&lt;/em&gt; is a method is convenient for the library but this library is stuck forever behind these two methods.&lt;br /&gt;jQuery, at current ECMAScript status, &lt;strong&gt;will never be able to switch gradually to real getters and setters&lt;/strong&gt; ... why that? A simple example:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;$("body").html; // returns the string in jQuery 3000&lt;br /&gt;&lt;br /&gt;$("body").html(); // shows a "deprecated warning"&lt;br /&gt;// ... and returns the "html" getter&lt;br /&gt;&lt;br /&gt;// implementation example&lt;br /&gt;function setInnerHTML(node) {&lt;br /&gt;  node.innerHTML = this;&lt;br /&gt;}&lt;br /&gt;Object.defineProperty($.fn, "html", {&lt;br /&gt;  get: function () {&lt;br /&gt;    return this[0].innerHTML;&lt;br /&gt;  },&lt;br /&gt;  set: function (html) {&lt;br /&gt;    this.each(setInnerHTML, html);&lt;br /&gt;  }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// the deprecation warning&lt;br /&gt;$.fn.__noSuchMethod__(function (property, args) {&lt;br /&gt;  if (property in this) {&lt;br /&gt;    console.log("Warning: " + property + " is not a method anymore");&lt;br /&gt;    if (args.length) {&lt;br /&gt;      // invoke the setter&lt;br /&gt;      this[property] = args[0];&lt;br /&gt;      // preserve behavior&lt;br /&gt;      return this;&lt;br /&gt;    } else {&lt;br /&gt;      // invoke the getter&lt;br /&gt;      return this[property];&lt;br /&gt;    }&lt;br /&gt;  } else {&lt;br /&gt;    throw "Y U NO READ DOCUMENTATION";&lt;br /&gt;  }&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's it, we can migrate from two different APIs implementing getters and setters whenever we had a similar behavior and bringing gracefully users to the new usage ... no wa can't!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;It Is Not About jQuery&lt;/h3&gt;I don't even use jQuery so don't get me wrong, this is not my battle here ... the point is that for another private project I am working on I would like to educate developers to use properties correctly but I understand developers may already got use to invoke methods as if it is normal, even when they are simply looking for a getter behavior.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var o = {&lt;br /&gt;  whatever:"cool bro",&lt;br /&gt;  __noSuchMethod__: function (property, args) {&lt;br /&gt;    console.log("we got a bro-blem here, " +&lt;br /&gt;      "don't invoke if you want a getter");&lt;br /&gt;    return this[property];&lt;br /&gt;  }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// so that &lt;br /&gt;o.whatever === o.whatever();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Secially last line of code is apparently impossible to reproduce with Proxies, those that suppose to be the new and best way to go, those that give us control on things rarely needed until now, those that made JS.Next group decide that &lt;em&gt;__noSuchMethod__&lt;/em&gt; was evil and it had to be abandoned.&lt;br /&gt;I really hope that JS.Next will not be &lt;em&gt;non-developer expectations behaviors driven&lt;/em&gt; because guys, somebody tries to do cool things with this cool language, and if the reason you drop something is because &lt;em&gt;we are all morons&lt;/em&gt;, as example misunderstanding the difference of a referenced property through parenthesis  ... oh well ...  good luck kkfuture JavaScript ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;How To Solve This&lt;/h3&gt;Please put an &lt;strong&gt;invoke&lt;/strong&gt; or even better an &lt;strong&gt;invokeProperty&lt;/strong&gt;, preserving &lt;em&gt;invoke&lt;/em&gt; for when the object itself is used as if it was callable, in the current Proxy specifications so that who knows what is doing, can keep doing it and who never even bothered with this stuff, won't be affected at all.&lt;br /&gt;Thank you for listening.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-3643006474638852079?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/3643006474638852079/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=3643006474638852079" title="16 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/3643006474638852079" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/3643006474638852079" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/Y3Cc8gG9gpc/please-give-us-back-nosuchmethod.html" title="Please, Give Us Back __noSuchMethod__ !" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>16</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/12/please-give-us-back-nosuchmethod.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-1021140272600815513</id><published>2011-12-12T19:19:00.012+01:00</published><updated>2011-12-12T22:07:30.323+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="process" /><category scheme="http://www.blogger.com/atom/ns#" term="build" /><category scheme="http://www.blogger.com/atom/ns#" term="structure" /><category scheme="http://www.blogger.com/atom/ns#" term="minification" /><category scheme="http://www.blogger.com/atom/ns#" term="Builder" /><title type="text">Create a JS builder with node.js</title><content type="html">A very good and common practice with JS projects bigger than 100 lines of code is to split code in different files.&lt;br /&gt;Benefits are clear:&lt;ul&gt;&lt;li&gt;smaller pieces of code to maintain&lt;br /&gt;&lt;/li&gt;&lt;li&gt;swappable portions for experiments and/or improvements or new features, as example including for a build &lt;em&gt;magic2.js&lt;/em&gt; and get it, rather than change drastically &lt;em&gt;magic.js&lt;/em&gt; and follow the repository logs&lt;/li&gt;&lt;li&gt;better organization of the code, and I'll come back on this in this post&lt;/li&gt;&lt;li&gt;possibility to distribute bigger closures, as example the jQuery approach&lt;/li&gt;&lt;li&gt;create ad hoc builds including or excluding portion of the library, specially suitable for specific version of the code that must be compatible with IE only&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Solutions All Over The Place&lt;/h3&gt;There are really tons of solutions able to make the described build process easy to use and easy to go. As example, I have created my own one and I am using it with basically every project I am working with: the &lt;a href="http://code.google.com/p/javascript-builder/"&gt;JavaScript Builder&lt;/a&gt;.&lt;br /&gt;However, this builder requires a couple of extra technologies such Python and Java ... but aren't we using simply JavaScript?&lt;br /&gt;So why not an easy to create guide on &lt;em&gt;how to build your code via JS only&lt;/em&gt;?&lt;br /&gt;This is what this post is about, and I hope you'll find useful.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;How To Structure Your Project&lt;/h3&gt;If all files are in the same directory is not easy to find the right file immediately since these could be many. A good solution I came up with is &lt;em&gt;folder related structure with both namespaces and private keywords paths&lt;/em&gt;.&lt;br /&gt;Here an example on how I would structure this library ( and please ignore the library itself )&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var myLib = (function (global, undefined) {"use strict";&lt;br /&gt;&lt;br /&gt;  // private scope function&lt;br /&gt;  function query(selector) {&lt;br /&gt;    return document.querySelectorAll(selector);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  function Wrapper(nodeList) {&lt;br /&gt;    this.length = nodeList.length;&lt;br /&gt;    this._list = nodeList;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  // a prototype method of the Wrapper "class"&lt;br /&gt;  Wrapper.prototype.item = function item(i) {&lt;br /&gt;    return this._list[i];&lt;br /&gt;  };&lt;br /&gt;&lt;br /&gt;  // public static query method&lt;br /&gt;  query.asWrapper = function (selector) {&lt;br /&gt;    return new Wrapper(query(selector));&lt;br /&gt;  };&lt;br /&gt;&lt;br /&gt;  var // private scope variables&lt;br /&gt;    document = global.document,&lt;br /&gt;    slice = [].slice&lt;br /&gt;  ;&lt;br /&gt;&lt;br /&gt;  // the actual object/namespace&lt;br /&gt;  return {&lt;br /&gt;    query: query,&lt;br /&gt;    internals: {&lt;br /&gt;      Wrapper: Wrapper&lt;br /&gt;    }&lt;br /&gt;  };&lt;br /&gt;&lt;br /&gt;}(this));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The code should be easy enough to understand. The object used as namespace for &lt;em&gt;myLib&lt;/em&gt; has a couple of methods, few private variables and functions and something exposed through the &lt;em&gt;internals&lt;/em&gt; namespace.&lt;br /&gt;It does not matter what the library does or how good/badly is structured, what matters is that our folder structure should be smart enough to be able to scale with any sort of allowed JS pattern ... OK?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Folder&lt;/h3&gt;Well, to start with, let's say our source code should be inside an &lt;em&gt;src&lt;/em&gt; folder so we can add other folders for tests or builds beside in the same hierarchy.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;dist&lt;br /&gt;src&lt;br /&gt;tests&lt;br /&gt;builder.js&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We'll see the builder.js later, in the meanwhile, let's have a look into the src folder:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;dist&lt;br /&gt;src&lt;br /&gt;    intro.js&lt;br /&gt;    outro.js&lt;br /&gt;    var.js&lt;br /&gt;    function&lt;br /&gt;        Wrapper.js&lt;br /&gt;        query.js&lt;br /&gt;        Wrapper&lt;br /&gt;            prototype&lt;br /&gt;                item.js&lt;br /&gt;        query&lt;br /&gt;            asWrapper.js&lt;br /&gt;tests&lt;br /&gt;builder.js&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The distinction will be much cleaner once you read above list through your editor or even your shell ... query and files are well distributed but bear in mind this is only the first example.&lt;br /&gt;Let's see what we are going to write into each file ?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/intro.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;var myLib = (function (global, undefined) {"use strict";&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/function/query.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;  // private scope function&lt;br /&gt;  function query(selector) {&lt;br /&gt;    return document.querySelectorAll(selector);&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/function/Wrapper.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;  function Wrapper(nodeList) {&lt;br /&gt;    this.length = nodeList.length;&lt;br /&gt;    this._list = nodeList;&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/function/Wrapper/prototype/item.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;  // a prototype method of the Wrapper "class"&lt;br /&gt;  Wrapper.prototype.item = function item(i) {&lt;br /&gt;    return this._list[i];&lt;br /&gt;  };&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/function/query/asWrapper.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;  // public static query method&lt;br /&gt;  query.asWrapper = function (selector) {&lt;br /&gt;    return new Wrapper(query(selector));&lt;br /&gt;  };&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/var.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;  var // private scope variables&lt;br /&gt;    document = global.document,&lt;br /&gt;    slice = [].slice&lt;br /&gt;  ;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;src/outro.js&lt;/strong&gt;&lt;pre class="code"&gt;&lt;br /&gt;  // the actual object/namespace&lt;br /&gt;  return {&lt;br /&gt;    query: query,&lt;br /&gt;    internals: {&lt;br /&gt;      Wrapper: Wrapper&lt;br /&gt;    }&lt;br /&gt;  };&lt;br /&gt;&lt;br /&gt;}(this));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Got it?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Structure Rules&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;every part of the scope can be distributed&lt;/li&gt;&lt;li&gt;each file can or cannot be compatible as stand alone with a parser because to test the library &lt;strong&gt;we need to build it first&lt;/strong&gt; ( eventually with automations )&lt;/li&gt;&lt;li&gt;function declarations should be included in a dedicated folder called &lt;em&gt;function&lt;/em&gt; accordingly with the nested level&lt;/li&gt;&lt;li&gt;var declaration &lt;strong&gt;per scope&lt;/strong&gt; could be included in a folder &lt;em&gt;var&lt;/em&gt; accordingly with the nested level. Do not create a var folder per each function where you define variables 'cause if you need it it means the function is too complex. Split it in sub task and do not define 100 variables per a single function: closures are the only exception.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;nested closure must be named in order to be able to define nested closure structure following previous rules. Every minifier will be able to remove function expression names, included named closures, while not every developer would like to deeply understand the whole code to recognize why the nested closure was useful. A classic example is the inclusion inside our own closure of an external library that uses its own closure. in this case name that closure so you know were to look for the library inside your folder structure.&lt;/li&gt;&lt;li&gt;function prototypes should be placed inside a prototype folder, inside the function folder.&lt;br /&gt;&lt;strong&gt;We don't need to reassign an object when we want to pollute the function prototype&lt;/strong&gt; so please stop this awkward common practice ASAP: &lt;code&gt;MyFunction.prototype = { /* THIS IS WRONG */ }&lt;/code&gt; and use the already available prototype object defined by default in every ECMAScript standard and per each function declaration or expression.&lt;br /&gt;If your argument is that the code will be bigger, use the outer scoped variables definition to address the prototype once and reuse this reference within the prototype folder. This approach will make your life easier once you get use to work with structured and distributed JavaScript files.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Specially about last example, we could have set a shortcut to the Wrapper.prototype object in the &lt;em&gt;var.js&lt;/em&gt; file and reuse the reference inside Wrapper.&lt;br /&gt;The structured folders will always help you to find references in the library thanks to the lookup that you, as well as the code, have to do.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;    // in the var.js file&lt;br /&gt;    WrapperPrototype = Wrapper.prototype,&lt;br /&gt;&lt;br /&gt;    // in the Wrapper/prototype/item.js file&lt;br /&gt;    WrapperPrototype.item = function item(i) { ... };&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Order Partially Matters&lt;/h3&gt;In ECMAScript 3rd or higher edition &lt;strong&gt;function declarations are always available at the very beginning of the scope&lt;/strong&gt;. I really don't know why these are so much underrated in daily basis code ... the fact these are always available means we can reference their prototype at any moment in our code:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var internalProto = (function () {&lt;br /&gt;&lt;br /&gt;    // address any declaration made in this scope&lt;br /&gt;    var WhateverPrototype = Whatever.prototype;&lt;br /&gt;    return WhateverPrototype;&lt;br /&gt;&lt;br /&gt;    // even if defined after a return!!!&lt;br /&gt;    function Whatever() {}&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;alert(internalProto); // [object Object]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, the above code is simply a demonstration about how function declarations work ... &lt;strong&gt;I am not suggesting a return in the middle, and declarations after&lt;/strong&gt;, all I am saying is that the order of things in JavaScript may not be relevant, and function declarations are a perfect example.&lt;br /&gt;Another example is the usage of variables ... if a function, as declaration or as expression, reference a variable defined in the outer scope &lt;strong&gt;nothing will break&lt;/strong&gt; unless we are invoking that function before the referenced variable has been defined.&lt;br /&gt;&lt;br /&gt;This are really &lt;strong&gt;ABC concepts&lt;/strong&gt; we all should know about JS before even claiming that we know JavaScript ... OK?&lt;br /&gt;Is really important to get these points because to simplify ASAP the builder file we need to rely in these assumptions.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The builder.js File&lt;/h3&gt;It's time to create the magic file that will do the job for us in possibly a smart way so that we can cover all edge cases we could think of.&lt;br /&gt;This is the content of &lt;strong&gt;builder.js&lt;/strong&gt; file, in the root of our project&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// @name        builder.js&lt;br /&gt;// @author      Andrea Giammarchi&lt;br /&gt;// @license     Mit Style License&lt;br /&gt;&lt;br /&gt;// list of files to include&lt;br /&gt;var&lt;br /&gt;  scriptName = "myLib", // the namespace/object.project name&lt;br /&gt;  fileList = [&lt;br /&gt;    "intro.js",    // beginning of the closure&lt;br /&gt;    "var.js",      // all declared variables&lt;br /&gt;    "function/*",  // all declared functions&lt;br /&gt;    "function/Wrapper/prototype/*", // all methods&lt;br /&gt;    "function/query/*", // all public statics&lt;br /&gt;    "outro.js"     // end of the library&lt;br /&gt;  ],&lt;br /&gt;  fs = require("fs"),  // file system module&lt;br /&gt;  out = [],            // output&lt;br /&gt;  alreadyParsed = []   // parsed files for visual feedback&lt;br /&gt;;&lt;br /&gt;&lt;br /&gt;// per each file in the list ...&lt;br /&gt;fileList.forEach(function addFile(file) {&lt;br /&gt;  // if the file contains a wild char ...&lt;br /&gt;  if (file.charAt(file.length - 1) == "*") {&lt;br /&gt;    // read the directory and per each file found there ..&lt;br /&gt;    fs.readdirSync(&lt;br /&gt;      __dirname + "/src/" + file.slice(0, -2)&lt;br /&gt;    ).forEach(function (file) {&lt;br /&gt;      // if the file type is js&lt;br /&gt;      // and the file has not been defined explicitly&lt;br /&gt;      // in the original list&lt;br /&gt;      if (&lt;br /&gt;        file.slice(-3) == ".js" &amp;&amp;&lt;br /&gt;        fileList.indexOf(file) &lt; 0&lt;br /&gt;      ) {&lt;br /&gt;        // call this same function providing the whole path&lt;br /&gt;        addFile(this + file);&lt;br /&gt;      }&lt;br /&gt;       // the path is passed as context to simplify the logic&lt;br /&gt;    }, file.slice(0, -1));&lt;br /&gt;  // if the file has not been included yet&lt;br /&gt;  } else if (alreadyParsed.indexOf(file) &lt; 0){&lt;br /&gt;    // put it into the list of already included files&lt;br /&gt;    alreadyParsed.push(file);&lt;br /&gt;    // add the file content to the output&lt;br /&gt;    out.push(fs.readFileSync(__dirname + "/src/" + file));&lt;br /&gt;  } else {&lt;br /&gt;    // if here, we are messing up with inclusion order&lt;br /&gt;    // or files ... it's a nice to know in console&lt;br /&gt;    try {&lt;br /&gt;      console.log("duplicated entry: " + file);&lt;br /&gt;    } catch(e) {&lt;br /&gt;      // shenanigans&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// put all ordered content into the destination file inside the dist folder&lt;br /&gt;fs.writeFileSync(__dirname + "/dist/" + scriptName + ".js", out.join("\n"));&lt;br /&gt;&lt;br /&gt;// that's it&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The reason there are so many checks if a wild char is encountered is quite simple ... the order may not matter but in some case the order matters.&lt;br /&gt;If as example a prototype property is used runtime to define other prototype methods or properties, this cannot be pushed in the output randomly but at the very beginning, example&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// src/function/Wrapper/prototype/behavior.js&lt;br /&gt;WrapperPrototype.behavior = "forEach" in [];&lt;br /&gt;&lt;br /&gt;// src/function/Wrapper/prototype/forEach.js&lt;br /&gt;WrapperPrototype.forEach = WrapperPrototype.behavior ?&lt;br /&gt;  function (callback) {[].forEach.call(this._list, callback, this)} :&lt;br /&gt;  function (callback) { /* a shim for non ES5 compatible browsers */ }&lt;br /&gt;;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Being file 2 strongly dependent on file 1, the list of files could be written as this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  fileList = [&lt;br /&gt;    "intro.js",    // beginning of the closure&lt;br /&gt;    "var.js",      // all declared variables&lt;br /&gt;    "function/*",  // all declared functions&lt;br /&gt;    "function/Wrapper/prototype/behavior.js", // precedence&lt;br /&gt;    "function/Wrapper/prototype/*", // all methods&lt;br /&gt;    "function/query/*", // all public statics&lt;br /&gt;    "outro.js"     // end of the library&lt;br /&gt;  ],&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;When the wild char will be encountered and the behavior passed to the forEach, this will be simply ignored since it has been pushed already in the previous call.&lt;br /&gt;Same concept could happen if a specific file must be parsed runtime at the end:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  fileList = [&lt;br /&gt;    "function/Wrapper/prototype/behavior.js", // precedence&lt;br /&gt;    "function/Wrapper/prototype/*", // all methods&lt;br /&gt;    "function/Wrapper/prototype/doStuff.js" // after all&lt;br /&gt;  ],&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I believe these are already edge cases most of the time but at least now we can better understand what the builder will do.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;How To Use The Builder&lt;/h3&gt;In console, inside the project folder where the &lt;em&gt;builder.js&lt;/em&gt; is:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;node builder.js&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's pretty much it ... if you try to open &lt;em&gt;dist/myLib.js&lt;/em&gt; after above call you will find your beautiful library all in one piece and ready to be minified, debugged, and tested.&lt;br /&gt;If the process does not take long time you may bind the builder to the &lt;em&gt;Constrol+S&lt;/em&gt; action with a potential sentinel able to inform you if any problem occurred, as example checking if the output has been polluted with some redundant file logged through the process.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;All these techniques may be handy for many reasons. First of all it's always good to maintain a structure, rather than a single file with thousands of lines of code, and secondly once we understand how the process work, nothing can stop us to improve, change, make it ad-hoc for anything we may need such regular expressions to strip out some code before the output push or whatever else could come up for some reason at some point.&lt;br /&gt;&lt;strong&gt;The minification&lt;/strong&gt; can be done the way you prefer, as example adding this single line of code at the end of the process assuming you have a &lt;em&gt;jar&lt;/em&gt; folder with, as example, google closure compiler.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;require('child_process').exec(&lt;br /&gt;  ['java -jar "',&lt;br /&gt;    __dirname + "/jar/compiler.jar",&lt;br /&gt;  '" --compilation_level=SIMPLE_OPTIMIZATIONS --language_in ECMASCRIPT5_STRICT --js "',&lt;br /&gt;    __dirname + "/dist/" + scriptName + ".js",&lt;br /&gt;  '" --js_output_file "',&lt;br /&gt;    __dirname + "/dist/" + scriptName + ".min.js",&lt;br /&gt;  '"'].join(""),&lt;br /&gt;  function (error, stdout, stderr) {&lt;br /&gt;    if (error) console.log(stderr);&lt;br /&gt;  }&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Enjoy your new builder :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-1021140272600815513?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/1021140272600815513/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=1021140272600815513" title="18 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/1021140272600815513" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/1021140272600815513" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/ul3hPHdR9nE/create-js-builder-with-nodejs.html" title="Create a JS builder with node.js" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>18</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/12/create-js-builder-with-nodejs.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-4048523001362663624</id><published>2011-12-06T01:30:00.006+01:00</published><updated>2011-12-06T02:27:08.324+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JSON" /><category scheme="http://www.blogger.com/atom/ns#" term="comments" /><title type="text">On JSON Comments</title><content type="html">Another active exchange with &lt;a href="https://twitter.com/getify"&gt;@getify&lt;/a&gt; about &lt;a href="http://bettween.com/webreflection/getify"&gt;JSON comments&lt;/a&gt; and here my take because tweets are cool but sometimes is hard to tell everything you think in 140 bytes ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Kyle Facts&lt;/h3&gt;JSON is used on daily basis for billion of things and configuration files are one, surely common, way to use JSON ( just think about npm packages for node.js ).&lt;br /&gt;His frustration about the fact JSON does not allow comments is comprehensible, and he even created an online petition about &lt;a href="http://52r.geti.fi/json-comments/petition"&gt;allowing comments in JSON specs&lt;/a&gt; ... but are comments really what we need?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Just A Side Effect&lt;/h3&gt;JSON is extremely attractive as standard, first of all because it's available and widely adopted by basically any programming language in this world, even those that never had to deal with a single JavaScript interlocutor, secondly because it's both simple to parse, and easy to read for humans.&lt;br /&gt;After all, what can be so wrong about comments inside such common serialization standard?&lt;br /&gt;Aren't comments just as easy to parse as white spaces?&lt;br /&gt;The problem is, in my opinion, that we are mixing up an easy process to serialize data, much easier compared to what PHP &lt;em&gt;serialize&lt;/em&gt; and &lt;em&gt;unserialize&lt;/em&gt; functions do, with the possibility to describe it.&lt;br /&gt;I have always seen JSON as a protocol, rather than a &lt;a href="http://yaml.org/"&gt;YAML&lt;/a&gt; substitute, and as a protocol I expect to be as compact as possible and as cross platform as possible.&lt;br /&gt;Specially about the latter point:&lt;br /&gt;&lt;blockquote cite="getify"&gt;&lt;a href="https://twitter.com/#!/getify/status/143847951993806848"&gt;that's annoying to port to every single language&lt;/a&gt;&lt;/blockquote&gt;Precisely, what we should understand is that if JSON became so popular without needing comments, maybe the fact today we would like to use it as a "&lt;i&gt;descriptive markup&lt;/i&gt;" does not reflect anymore the success, the adoption, and possibilities this standard brought to all these languages?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Improve The Standard&lt;/h3&gt;Thanks gosh software is not always stuck behind immutable standards or patents ... and neither is JSON.&lt;br /&gt;If the need for comments is such big topic, define another standard able to combine the good old one with a new one.&lt;br /&gt;If this new standard is truly what developers need, every JSON implementor will spend few hours to test and optimize the well defined standard in order to accept comments, isn't it?&lt;br /&gt;I mean ... &lt;a href="http://www.ietf.org/rfc/rfc4627.txt"&gt;RFC 4627&lt;/a&gt; was not meant to be the final solution, that was a Crockford proposal universally adopted.&lt;br /&gt;To create a new standard able to extend RFC 4627 should not be a big problem ... or maybe ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;JSON Is Not A JavaScript Thing&lt;/h3&gt;The JSON serialization looks just like JavaScript ... but not JavaScript only.&lt;br /&gt;Other programming languages use curly brackets and squared brackets to define lists and objects ( Python and others ) ... the fact JSON has been accepted so well is probably because the design of the format was indeed already widely adopted, it was not a JS thing, and never should be.&lt;br /&gt;What's the deal here, is define a standard for JSON comments.&lt;br /&gt;Let me better explain this point ... &lt;br /&gt;&lt;br /&gt;I am a JS developer and I edit my JSON files via my JS editor ... fair enough ... I want to communicate my data to a server side service, let's say Python.&lt;br /&gt;Python would like to be able to parse my data and produce a file compatible with ... Python, of course.&lt;br /&gt;Does it mean that Python at that point should keep comments in a JavaScript standard? And why that, since the format used to exchange data was already somehow evaluable via Python and right now not anymore due some double slash in the file?&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;# this is PYTHOOOOOOOOOON&lt;br /&gt;o = {"test": "data"}&lt;br /&gt;o.get("test") # data&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Will the renewed JSON work as well?&lt;br /&gt;&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;# still python&lt;br /&gt;o = {"test": "data"} // and some WTF&lt;br /&gt;o.get("test")&lt;br /&gt;&lt;br /&gt;&gt;&gt; SyntaxError: invalid syntax&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Well done ... making JSON with comments a JS thing python, as other languages, need extra effort to parse data.&lt;br /&gt;What will happen once Python uses the json library?&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;import json&lt;br /&gt;&lt;br /&gt;jsonh.loads(theReceivedData);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Should it print data with python compatible comments or with JS compatible comments so that data is not directly usable anymore for any python application, storing it as example in a file.py or a database ?&lt;br /&gt;And once the renewed JSON has been transformed into Python valid syntax, wouldn't this file not be usable anymore from all others programming languages due possible syntax errors ?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Not That Easy&lt;/h3&gt;I like JSON as it is, except few broken implementations quite common even on browsers, because it's about creating a bloody piece of text many other languages can understand basically on the fly.&lt;br /&gt;No need to remember which comment style has been saved with that version of JSON, no need to parse back and finally, no need to ask every single programming language that is using JSON as protocol to update their legacy ... that just worked, and it will aways work for what it was meant: transfer data, not transfer JS like code without functions and/or functions calls only ...&lt;br /&gt;What we are doing, we as JavaScript developer, is to abuse JSON as if it's a piece of our JS code, polluting today with comments, and who knows what else tomorrow.&lt;br /&gt;The right way to go, still in my opinion, would be, once again, to enrich, propose, create, a new standard that allows comments and why not, other features.&lt;br /&gt;As example, what I always found annoying is that in PHP we can unserialize preserving the class, so that we can serialize objects states ... where is this in JSON?&lt;br /&gt;Nowhere, indeed &lt;a href="http://webreflection.blogspot.com/2007/06/jsomon-json-evolution.html"&gt;I have spent in my past&lt;/a&gt; few hours &lt;a href="http://webreflection.blogspot.com/2010/04/json-sleep-wakeup-serialize-and.html"&gt;trying to enrich this protocol&lt;/a&gt; ... did it work? Was it interesting ? Probably not, except for my last attempt that is 100% based on current JSON and it's about optimizing bandwidth and performances ... that worked better, accordingly with &lt;a href="https://github.com/WebReflection/JSONH"&gt;JSONH github status&lt;/a&gt;, still I was not expecting every other that never had this problem to adopt that approach ... you know what I mean?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Still Valid JSON&lt;/h3&gt;If it's about writing comments, next snippet is perfectly valid JSON string. All we need to do is to use the replacer in a proper way:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;{&lt;br /&gt;  "@description": "something meaningful",&lt;br /&gt;   "property": "value",&lt;br /&gt;&lt;br /&gt;  "@description": "something else",&lt;br /&gt;  "other": "other value"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// parse above text via JSON&lt;br /&gt;console.log(JSON.parse(aboveText, function (key, value){&lt;br /&gt;  if (key.charAt(0) != "@")&lt;br /&gt;    return value;&lt;br /&gt;}));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here we are with our object, comments manually written on the original JSON, and every language able to parse them&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-4048523001362663624?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/4048523001362663624/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=4048523001362663624" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/4048523001362663624" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/4048523001362663624" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/1wHKmYLs6r4/on-json-comments.html" title="On JSON Comments" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>5</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/12/on-json-comments.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-2603321261506692989</id><published>2011-11-30T20:28:00.015+01:00</published><updated>2011-11-30T22:05:22.702+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Array" /><category scheme="http://www.blogger.com/atom/ns#" term="Object" /><category scheme="http://www.blogger.com/atom/ns#" term="extras" /><category scheme="http://www.blogger.com/atom/ns#" term="prototype" /><title type="text">Array extras and Objects</title><content type="html">When &lt;a href="https://developer.mozilla.org/en/New_in_JavaScript_1.6"&gt;Array extras&lt;/a&gt; landed in JavaScript 1.6 I had, probably together with other developers, one of those &lt;em&gt;HOORRAYYY&lt;/em&gt; moment ...&lt;br /&gt;What many libraries and frameworks out there still implement, is this sort of universal &lt;em&gt;each&lt;/em&gt; method that supposes to be compatible with both Arrays and Objects.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A Bit Messed Up&lt;/h3&gt;What I have never liked that much about these &lt;em&gt;each&lt;/em&gt; methods is that we have to know in advance in any case if the object we are passing is an Array, an ArrayLike one, or an Object.&lt;br /&gt;In latter case, the callback passed as second argument will receive as second argument &lt;em&gt;the key&lt;/em&gt;, and not &lt;em&gt;the index&lt;/em&gt;, which simply means we cannot trust a generic callback unless this does not check per each iterated item the second argument type, or unless we don't care at all about the second argument.&lt;br /&gt;In any case I always found this a bad design. If we think about events, as example, it's totally natural to expect a single argument as event object and then we can act accordingly.&lt;br /&gt;This let us reuse callbacks for similar purpose and maintain a &lt;abbr title="Don't Repeat Yourself"&gt;DRY&lt;/abbr&gt; code.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Need For An Object#forEach&lt;/h3&gt;All implementation of each, and as far as I know with the only exception of jQuery which makes things even more complicated since we generally have to completely ignore the first argument in this case, have some natural confusion inside the method.&lt;br /&gt;If you take the &lt;a href="http://documentcloud.github.com/underscore/"&gt;underscore.js&lt;/a&gt; library, as example, you will note that there are two aliases for the &lt;em&gt;each&lt;/em&gt; method, each itself and forEach, so it's more than clear for me that JS developers are clearly missing an &lt;em&gt;Array#forEach&lt;/em&gt; like method in order to iterate with objects, rather than lists.&lt;br /&gt;It must be also underlined that all these methods are somehow error prone: what if the object we are passing has a &lt;em&gt;length&lt;/em&gt; property that does not necessary mean it points to the length of items stored via index as if it was an Array?&lt;br /&gt;You may consider this an edge case, or an anti pattern, then you have to remember that &lt;em&gt;functions&lt;/em&gt; in JavaScript are first class objects.&lt;br /&gt;Probably all these methods will nicely fail indeed with functions, passed as objects, whenever you decide that your function can be used as object too.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var whyNot = function (obj) {&lt;br /&gt;  /* marvelous stuff here */&lt;br /&gt;  this.calls++;&lt;br /&gt;  return this.doStuff(obj);&lt;br /&gt;};&lt;br /&gt;whyNot.calls = 0;&lt;br /&gt;whyNot.doStuff = function (obj) {&lt;br /&gt;  /* kick-ass method */&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// the unexpected but allowed&lt;br /&gt;whyNot = whyNot.bind(whyNot);&lt;br /&gt;&lt;br /&gt;whyNot.length; // 1&lt;br /&gt;whyNot[0];        // undefined&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;By design, the length of any function in JavaScript is &lt;em&gt;read-only&lt;/em&gt; and means nothing, in therms of Array iteration, it simply means the number of arguments the function defined during its declaration/definition as expression.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;WTF&lt;/h3&gt;Whenever above example makes sense or not, I am pros patterns exploration and when a common method is not compatible with all scenarios, I simply think something went wrong or is missing in the language.&lt;br /&gt;Thanks gosh JS is freaking flexible and with ES5 we can define some prototype without affecting &lt;em&gt;for( in )&lt;/em&gt; loops but hopefully simplifying our daily basis stuff.&lt;br /&gt;Remember? With underscore or others we still have to know in advance if the passed object is an Array, an ArrayLike, or a generic object ... so what would stop us to simply chose accordingly?&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// Array or ArrayLike&lt;br /&gt;[].forEach.call(genericArrayLike, callbackForArrays);&lt;br /&gt;&lt;br /&gt;// generic object to iterate&lt;br /&gt;{}.forEach.call(object, callbackForObjects);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;An explicit choice in above case is the fastest and most reliable way we have to do things properly. A DOM collection, as well as any array or arrayLike object will use the native forEach, but we can still recycle callbacks designed to deal with &lt;em&gt;value, key&lt;/em&gt; and objects, rather than &lt;em&gt;value, index&lt;/em&gt;, and this is the little experiment:&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Object extras&lt;/h3&gt;The concept of each callback is exactly the same of original, native, Array callbacks, except things are based on native functions available in all ES5 compatible desktop and basically all mobile browsers, and easy to shim with all others too old to deal with JS 1.6 or higher.&lt;br /&gt;&lt;br /&gt;&lt;script src="https://gist.github.com/1410420.js?file=Object.extra.js"&gt;&lt;/script&gt;&lt;br /&gt;&lt;br /&gt;Here a couple of examples:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var o = {a:"a", b:"b", c:""};&lt;br /&gt;&lt;br /&gt;// know if all values are strings&lt;br /&gt;o.every(function (value, key, object) {&lt;br /&gt;  return typeof value == "string";&lt;br /&gt;}); // true&lt;br /&gt;&lt;br /&gt;// filter by content, no empty strings&lt;br /&gt;var filtered = o.filter(function (value, key, object) {&lt;br /&gt;  return value.length;&lt;br /&gt;}); // {a:"a",b:"b"} // original object preserved&lt;br /&gt;&lt;br /&gt;// loop through all values (plus checks)&lt;br /&gt;o.forEach(function (value, key, object) {&lt;br /&gt;  object === o; // true&lt;br /&gt;  this === o;    // true&lt;br /&gt;  if (key.charAt(0) != "_") {&lt;br /&gt;    doSomethingWithThisValue(value);&lt;br /&gt;  }&lt;br /&gt;}, o); // NOTE: all these methods respect Array extras signatures&lt;br /&gt;&lt;br /&gt;// map a new object&lt;br /&gt;var mapped = o.map(function (value, key, object) {&lt;br /&gt;  return value + 1;&lt;br /&gt;}); // {a:"a1",b:"b1"} // original object preserved&lt;br /&gt;&lt;br /&gt;// know if a value contains "a"&lt;br /&gt;o.some(function (value, key, object) {&lt;br /&gt;  return value === "a";&lt;br /&gt;}); // true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The reason &lt;em&gt;reduce&lt;/em&gt; and &lt;em&gt;reduceRight&lt;/em&gt; are not in the list is simple: which one would be the key to preserve, the first of the list? There is no such thing as "&lt;em&gt;predefined for/in order&lt;/em&gt;" in JavaScript plus these methods are more Array related so out of this experiment.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;Once minified and minzipped the gist weights about &lt;strong&gt;296 bytes&lt;/strong&gt; which is ridiculous size compared with any application we are dealing with on daily basis.&lt;br /&gt;Specially &lt;em&gt;forEach&lt;/em&gt;, but probably others too, may become extremely handy and ... of course, using the &lt;em&gt;Object.keys&lt;/em&gt; method internally, this is gonna be compatible with Arrays too but hey, the whole point was to make a clear distinction ;)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;[edited]&lt;br /&gt;&lt;h3&gt;The Misleading Signature&lt;/h3&gt;I don't know how many times I have spoken with jQuery developers, just because they are common, convinced that native &lt;em&gt;Array#forEach&lt;/em&gt; was accepting the value as &lt;strong&gt;second&lt;/strong&gt; argument.&lt;br /&gt;I always considered inverted signatures, whatever API it is, bad for both performances, no possibility to fallback into some native method, and learning curve, where new comers learn than a generic &lt;em&gt;each&lt;/em&gt; method must have the index as first argument.&lt;br /&gt;Bear in mind whenever we loop we are most likely interested into the value of that index or key, so this value should be the first, and if you need the only one, argument passed through the procedure.&lt;br /&gt;A completely ignored first argument is, once again and in my opinion, a bad design for an API: stuck without native power, teaching arguments order is not relevant.&lt;br /&gt;Well, specially latter point is true if we have named arguments, but in JS nothing have been planned so far, and in ES6 the way we gonna name arguments is still under discussion.&lt;br /&gt;&lt;br /&gt;Have fun with JS&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-2603321261506692989?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/2603321261506692989/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=2603321261506692989" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/2603321261506692989" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/2603321261506692989" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/Q7ROCOErff4/array-extras-and-objects.html" title="Array extras and Objects" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>6</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/array-extras-and-objects.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-7238362446865515823</id><published>2011-11-27T15:26:00.017+01:00</published><updated>2011-11-27T21:11:58.288+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="guide" /><category scheme="http://www.blogger.com/atom/ns#" term="style" /><title type="text">About Felix's Style Guide</title><content type="html">Style guides are good as long as these are meaningful and a bit "&lt;em&gt;open minded&lt;/em&gt;" because if one style is recognized as anti pattern then it must be possible to update/change it.&lt;br /&gt;&lt;br /&gt;The &lt;a href="http://nodeguide.com/style.html"&gt;Felix's Node.js Style Guide&lt;/a&gt; is surely a meaningful one, but I hope it's open minded too.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Why This Post&lt;/h3&gt;Because I write node.js code as well sometimes and I would like to write code accepted by the community. Since developers may go too religious about guides I don't want explain all these points per each present or future node.js module I gonna write ... I post it once, I will eventually update it, but it's here and I can simply point at this any time.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Style Guide Side Effect&lt;/h3&gt;As happened before with &lt;a href="http://javascript.crockford.com/code.html"&gt;the older one&lt;/a&gt; or &lt;a href="http://www.jslint.com/lint.html"&gt;the linter&lt;/a&gt;, a style guide may mislead developers and if they are too religious and unable to think about some point, the quality of the result code may be worse rather than better.&lt;br /&gt;I have talked about JSLint already too much in this blog so ... let's bring the topic in track and see what Felix may re-consider.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Quotes&lt;/h3&gt;Current status: &lt;em&gt;Use single quotes, unless you are writing JSON&lt;/em&gt;&lt;br /&gt;A common mistake for JavaScript developers, specially those with PHP, Ruby, or other scripting languages background, is to think that single quotes are different from double quotes ... sorry to destroy this myth guys but in JavaScript &lt;strong&gt;there is no difference between single and double quotes&lt;/strong&gt;.&lt;br /&gt;Once you get this, you must think that if by standard definition JSON uses double quotes there is no reason to prefer single quotes over double.&lt;br /&gt;What should this difference tell us, that one is JSON and one is JavaScript for node.js? Such assumption is a bit ridiculous to me since JSON &lt;strong&gt;is&lt;/strong&gt; JavaScript, nothing more, nothing less.&lt;br /&gt;More over, I am not a big fan of HTML strings inside JS files because of separation of concerns, and I'll come back on it, but in English, as well as in many other languages, the single quote inside a string is quite common, isn't it?&lt;br /&gt;Accordingly, are you really planning to prefer &lt;em&gt;'it\'s OK'&lt;/em&gt; over &lt;em&gt;"it's OK"&lt;/em&gt;?&lt;br /&gt;And if the suggested editor, in the guide itself, is one with supported syntax highlight, shouldn't we simply trust the highlighted string in order to recognize it, rather than distinguish between JSON and non JSON strings?&lt;br /&gt;Shouldn't we write comfortably without &lt;em&gt;silly rules&lt;/em&gt;, as Felix says in another point, so that we can chose whatever string delimiter we want accordingly with the content of the string?&lt;br /&gt;Last, but not least, for those convinced that in HTML there is any sort of difference between single and double quotes, I am sorry to, once again, destroy this myth since &lt;strong&gt;&lt;a href="http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2"&gt;there is no difference in HTML between quotes&lt;/a&gt;&lt;/strong&gt; ... so, once again, chose what you want and focus on something else than distinction between JSON and non JSON strings ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Variable declarations&lt;/h3&gt;Current status: &lt;em&gt;Declare one variable per var statement, it makes it easier to re-order the lines. Ignore Crockford on this, and put those declarations wherever they make sense.&lt;/em&gt;&lt;br /&gt;If there is one thing that I always agreed with Crockford is this one: &lt;strong&gt;variable declared at the beginning of the function&lt;/strong&gt;, with the exception for function declarations that should be before variable declarations, and not after.&lt;br /&gt;The reason is quite simple: wherever we declare a variable, this will be available at the very beginning of the scope so which place can be better than the beginning of the scope itself to instantly recognize all local scope variables rather than scrolling the whole closure 'till the end in order to find that name that completely screwed up the whole logic in the middle because is shadowing something else inside or outside the scope ?&lt;br /&gt;Is that easy, I don't want to read potentially thousands of lines of code to understand which variable has been defined where, I want a single bloody place to understand what is local and what is not.&lt;br /&gt;The only exception to this rule may be some temporary variable, as is the classic &lt;em&gt;i&lt;/em&gt; used in for loops, or some &lt;em&gt;tmp&lt;/em&gt; reference still common in for loops&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;// the exception ... in the middle of the code&lt;br /&gt;&lt;br /&gt;for (var i = 0, length = something.length, tmp; i &lt; length; ++i) {&lt;br /&gt;    tmp = something[i];&lt;br /&gt;    // do something meaningful &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Chances that above loop will destroy our logic because of a shadowed &lt;em&gt;i&lt;/em&gt; or &lt;em&gt;tmp&lt;/em&gt; reference are really rare and we should use meaningful variables name.&lt;br /&gt;As summary, there are only advantages on declaring variables on top, and until we have no &lt;em&gt;let&lt;/em&gt; statements it is only risky, and dangerous for our business, to define variables in the wild.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// how you may write code&lt;br /&gt;(function () {&lt;br /&gt;  return true;&lt;br /&gt;  var inTheWild = 123;&lt;br /&gt;  function checkTheWild() {&lt;br /&gt;    return inTheWild === 123;&lt;br /&gt;  }&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// how JS works in any case&lt;br /&gt;(function () {&lt;br /&gt;&lt;br /&gt;  // function declarations instantly available in the scope&lt;br /&gt;  function checkTheWild() {&lt;br /&gt;    return inTheWild === 123;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  // any var declaration instantly available as undefined&lt;br /&gt;  var inTheWild;&lt;br /&gt;&lt;br /&gt;  return true;&lt;br /&gt;&lt;br /&gt;  // no matters where/if we assign the value&lt;br /&gt;  // the inTheWild is already available everywhere&lt;br /&gt;  // with undefined as default value&lt;br /&gt;  // and before this assignment&lt;br /&gt;  inTheWild = 123;&lt;br /&gt;  &lt;br /&gt;  // shadows should be easy to track&lt;br /&gt;  // top of the function is the right place to track them&lt;br /&gt;}());&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Constants&lt;/h3&gt;Current status: &lt;em&gt;Constants should be declared as regular variables or static class properties, using all uppercase letters.&lt;br /&gt;&lt;br /&gt;Node.js / V8 actually supports mozilla's const extension, but unfortunately that cannot be applied to class members, nor is it part of any ECMA standard.&lt;/em&gt;&lt;br /&gt;I could not disagree more here ... the meaning of constant is something immutable and the reason we use constant is to believe these are immutable.&lt;br /&gt;Why on earth avoid a language feature when it provides exactly what we need? Don't we want more reliable code? And what about security?&lt;br /&gt;Neither in PHP we can &lt;a href="http://php.net/manual/en/function.define.php"&gt;define&lt;/a&gt; an object property and this does not mean we should avoid the usage of &lt;em&gt;define&lt;/em&gt; function, isn't it?&lt;br /&gt;Use &lt;em&gt;const&lt;/em&gt; as much as you want unless the code does not have to run cross platform ( browsers included ) and if you want to define constants with objects, use the JavaScript equivalent to do that.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;function define(object, property, value) {&lt;br /&gt;    Object.defineProperty(object, property, {&lt;br /&gt;        get: function () {&lt;br /&gt;            return value;&lt;br /&gt;        }&lt;br /&gt;        // if you really want to throw an error&lt;br /&gt;        // , set: function () {throw "unable to redefine " + property;}&lt;br /&gt;    });&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var o = {};&lt;br /&gt;define(o, "TEST", 123);&lt;br /&gt;o.TEST = 456;&lt;br /&gt;o.TEST; // 123&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I have personally proposed &lt;a href="http://webreflection.blogspot.com/2007/10/cow-javascript-define-php-like-function.html"&gt;cross platform ways to do the same&lt;/a&gt; without or &lt;a href="http://webreflection.blogspot.com/2011/10/objectprototypedefine-proposal.html"&gt;within objects themselves&lt;/a&gt;.&lt;br /&gt;As we can see there are many ways to define constants and if the argument is that const is not standard it's a weak one because nobody is planning to remove this keyword from V8 or SpiderMonkey, most likely every other browser will adopt this keyword in the future but if that won't happen, to find and replace it with &lt;em&gt;var&lt;/em&gt; only when necessary is a better way to go: security and features, we should encourage these things rather than ignore them, imho.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Equality operator&lt;/h3&gt;Current status: &lt;em&gt;Programming is not about remembering stupid rules. Use the triple equality operator as it will work just as expected.&lt;/em&gt;&lt;br /&gt;No it doesn't because coercion is not about equality only.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;alert("2" &lt; 3 &amp;&amp; 1 &lt; "2");&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Programming IS about remembering rules, that's the reason we need to know the syntax in order to code something ... right?&lt;br /&gt;&lt;strong&gt;Coercion must be understood rather than being ignored&lt;/strong&gt; and rules are pretty much simple and widely explained in the specs, &lt;a href="http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html"&gt;even more simplified in this old post of mine&lt;/a&gt;.&lt;br /&gt;If any of you developers still do this idiotic check &lt;strong&gt;you are doing it wrong&lt;/strong&gt;.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// WRONG!!!!!!!!!!!!!&lt;br /&gt;arg === null || arg === undefined&lt;br /&gt;&lt;br /&gt;// THE SAFER EXACT EQUIVALENT&lt;br /&gt;arg == null&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;You should rather avoid &lt;em&gt;undefined&lt;/em&gt; equality in any piece of code you wrote, unless you did not create an undefined reference by yourself.&lt;br /&gt;As summary, a good developer does not ignore problems, a good developer understands them and only after decide which way is the best one.&lt;br /&gt;Felix is a good developer and he should promote deeper knowledge ... this specific point was really bad because it's like saying "&lt;em&gt;avoid regular expressions because you don't understand them and you don't want to learn them&lt;/em&gt;".&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Extending prototypes&lt;/h3&gt;Current status: &lt;em&gt;Do not extend the prototypes of any objects, especially native ones&lt;/em&gt;&lt;br /&gt;&lt;a href="http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/"&gt;Read this article&lt;/a&gt; and stick an "&lt;em&gt;it depends&lt;/em&gt;" in your screen. Nobody wants to limit JS potentials and &lt;em&gt;Object.defineProperty/ies&lt;/em&gt; is a robust way to do things properly.&lt;br /&gt;Sure we must understand that even a method like &lt;em&gt;Array#empty&lt;/em&gt; could have different meanings ... e.g.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var arr = Array(3);&lt;br /&gt;// is arr empty ?&lt;br /&gt;// length is 3 but no index has been addressed&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;If we pollute native prototype we must agree on the meaning or we must prefix our extension so that nobody can complain if that empty was good enough or just a wrong concept.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// a meaningful Array#empty&lt;br /&gt;Object.defineProperty(Array.prototype, "empty", {&lt;br /&gt;  value: function empty() {&lt;br /&gt;    for (var i in this) return false;&lt;br /&gt;    return true;&lt;br /&gt;  }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;alert([&lt;br /&gt;  [].empty(),       // true&lt;br /&gt;  Array(3).empty(), // true&lt;br /&gt;  [null].empty()    // false&lt;br /&gt;]);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Conditions&lt;/h3&gt;Current status: &lt;em&gt;Any non-trivial conditions should be assigned to a descriptive variable&lt;/em&gt;&lt;br /&gt;I often write empty condition on purpose and to both avoid superflous re-assignment and speed up the code.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// WRONG&lt;br /&gt;object.property = object.property || defaultValue;&lt;br /&gt;&lt;br /&gt;// better&lt;br /&gt;object.property || (object.property = defaultValue):&lt;br /&gt;&lt;br /&gt;// RIGHT&lt;br /&gt;"property" in object || (object.property = defaultValue);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Why on earth would I assign that ? Same I would not do it if the condition is not reused at least twice.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;if (done.something() &amp;&amp; done.succeed) {&lt;br /&gt;    // done.something() &amp;&amp; done.succeed useful&lt;br /&gt;    // here and nowhere else in the code&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Accordingly with the fact spread variable declarations are a bad practice, I cannot think about creating flags all over the place for these kind of &lt;em&gt;one shot&lt;/em&gt; checks.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Function length&lt;/h3&gt;Current status: &lt;em&gt;Keep your functions short. A good function fits on a slide that the people in the last row of a big room can comfortably read. So don't count on them having perfect vision and limit yourself to ~10 lines of code per function.&lt;/em&gt;&lt;br /&gt;I agree on this point but JavaScript is all about functions.&lt;br /&gt;I understand the &lt;em&gt;require&lt;/em&gt; approach does not need a closure to surround the whole module, being this already somehow sandboxed, but cross platform code and private functions or variables are really common in JS so that a module may be entirely written inside a closure.&lt;br /&gt;A closure is a function so as long as this point is flexible is fine to me, also as long as the code is still readable and elegant ... I can already imagine developers writing &lt;strong&gt;10 lines of functions using all 80 characters per line&lt;/strong&gt; in order to respect this point ...&lt;br /&gt;&lt;br /&gt;&lt;img style="border:0" src="http://s3.amazonaws.com/ragefaces/fed47e7ffa874d01b771474d2eef1a60.png" width="320" /&gt;&lt;br /&gt;&lt;br /&gt;... now, that would be lame.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Object.freeze, Object.preventExtensions, Object.seal, with, eval&lt;/h3&gt;Current status: &lt;em&gt;Crazy shit that you will probably never need. Stay away from it.&lt;/em&gt;&lt;br /&gt;Felix here put language features together with "&lt;em&gt;language mistakes&lt;/em&gt;".&lt;br /&gt;With &lt;em&gt;"use strict"&lt;/em&gt; directive, the one Felix should have put at the very beginning of his guideline, &lt;em&gt;with&lt;/em&gt; statement is not even allowed.&lt;br /&gt;&lt;em&gt;eval&lt;/em&gt; has nothing to do with Object.freeze and others and these methods are part of the ES5 specification.&lt;br /&gt;It is true you may not need them, to define them as &lt;em&gt;something to stay away from&lt;/em&gt;, specially from somebody that said there are no constants for objects, is kinda limitative and a sort of non sense.&lt;br /&gt;Learn these new methods, and use them if you think/want/need.&lt;br /&gt;&lt;br /&gt;And that's all folks&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-7238362446865515823?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/7238362446865515823/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=7238362446865515823" title="13 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7238362446865515823" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7238362446865515823" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/RpBcACi2cHo/about-felixs-style-guide.html" title="About Felix's Style Guide" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>13</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/about-felixs-style-guide.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-8883226946059331960</id><published>2011-11-26T12:52:00.003+01:00</published><updated>2011-11-26T13:39:00.625+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JSON" /><category scheme="http://www.blogger.com/atom/ns#" term="JSONH" /><category scheme="http://www.blogger.com/atom/ns#" term="homogeneous" /><category scheme="http://www.blogger.com/atom/ns#" term="Collection" /><title type="text">JSONH New schema Argument</title><content type="html">The freaking fast and bandwidth saver &lt;a href="https://github.com/WebReflection/JSONH"&gt;JSONH Project&lt;/a&gt; has finally a new &lt;em&gt;schema&lt;/em&gt; argument added at the end of every method in order to make nested Homogeneous Collections automatically "&lt;i&gt;packable&lt;/i&gt;", here an example:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;            var&lt;br /&gt;                // nested objects b property&lt;br /&gt;                // have same homogeneous collections&lt;br /&gt;                // in properties c and d&lt;br /&gt;                schema = ["b.c", "b.d"],&lt;br /&gt;                &lt;br /&gt;                // test case&lt;br /&gt;                test = [&lt;br /&gt;                    {   // homogeneous collections in c and d&lt;br /&gt;                        b: {&lt;br /&gt;                            c: [&lt;br /&gt;                                {a: 1},&lt;br /&gt;                                {a: 2}&lt;br /&gt;                            ],&lt;br /&gt;                            d: [&lt;br /&gt;                                {a: 3},&lt;br /&gt;                                {a: 4}&lt;br /&gt;                            ]&lt;br /&gt;                        }&lt;br /&gt;                    }, {&lt;br /&gt;                        a: 1,&lt;br /&gt;                        // same homogeneous collections in c and d&lt;br /&gt;                        b: {&lt;br /&gt;                            c: [&lt;br /&gt;                                {a: 5},&lt;br /&gt;                                {a: 6}&lt;br /&gt;                            ],&lt;br /&gt;                            d: [&lt;br /&gt;                                {a: 7},&lt;br /&gt;                                {a: 8}&lt;br /&gt;                            ]&lt;br /&gt;                        }&lt;br /&gt;                    }&lt;br /&gt;                ]&lt;br /&gt;            ;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The &lt;em&gt;JSONH.pack(test, schema)&lt;/em&gt; output will be the equivalent of this string:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;[{"b":{"c":[1,"a",1,2],"d":[1,"a",3,4]}},{"a":1,"b":{"c":[1,"a",5,6],"d":[1,"a",7,8]}}]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;How Schema Works&lt;/h3&gt;It does not matter if the output is an object or a list of objects, as well as it does not matter if the output has nested properties.&lt;br /&gt;As soon as there is an homogeneous collection somewhere deep in the nested chain and common for all other levels, the schema is able to reach that property and optimize it directly.&lt;br /&gt;Objects inside objects do not need to be the same or homogeneous, these can simply have a unique property which is common for all items and this is enough to take advantage of the &lt;em&gt;schema&lt;/em&gt; argument that could be one string, or an array of strings.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Experimental&lt;/h3&gt;Not because it does not work, I have &lt;a href="https://github.com/WebReflection/JSONH/blob/master/js/test/jsonh.js"&gt;added tests indeed&lt;/a&gt;, simply because I am not sure 100% this implementation covers all possible cases but I would rather keep it simple and let developers deal with more complex scenario via manual parsing through the &lt;em&gt;JSONH.pack/unpack&lt;/em&gt; and without schema ... this is still possible as it has always been.&lt;br /&gt;Let me know what you think about the schema, if accepted, I will implement it in Python and PHP too, thanks.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-8883226946059331960?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/8883226946059331960/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=8883226946059331960" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8883226946059331960" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8883226946059331960" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/usaEVG46SbE/jsonh-new-schema-argument.html" title="JSONH New schema Argument" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>0</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/jsonh-new-schema-argument.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-2248627748932897780</id><published>2011-11-25T21:41:00.007+01:00</published><updated>2011-11-25T22:55:18.708+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="performances" /><category scheme="http://www.blogger.com/atom/ns#" term="recycle" /><category scheme="http://www.blogger.com/atom/ns#" term="defineProperties" /><title type="text">On Complex Getters And Setters</title><content type="html">A common use case for getters and setters is via scalar values rather than complex data.&lt;br /&gt;Well, this is just a programmer mind limit since data we could set, or get, can be of course much more complex: here an example&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;function Person() {}&lt;br /&gt;Person.prototype.toString = function () {&lt;br /&gt;    return this._name + " is " + this._age;&lt;br /&gt;};&lt;br /&gt;// the magic identity configuration object&lt;br /&gt;Object.defineProperty(Person.prototype, "identity", {&lt;br /&gt;    set: function (identity) {&lt;br /&gt;        // do something meaningful&lt;br /&gt;        this._name = identity.name;&lt;br /&gt;        this._age = identity.age;&lt;br /&gt;        // store identity for the getter&lt;br /&gt;        this._identity = identity;&lt;br /&gt;    },&lt;br /&gt;    get: function () {&lt;br /&gt;        return this._identity;&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;With above pattern we can automagically update a Person instance name and age through a single identity assignment.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var me = new Person;&lt;br /&gt;me.identity = {&lt;br /&gt;    name: "WebReflection",&lt;br /&gt;    age: 33&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;alert(me); // WebReflection is 33&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;While the example may not make much sense, the concept behind could be extended to any sort of property of any sort of class/instance/object.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;What's Wrong&lt;/h3&gt;The problem is that the setter does something in order to keep the object updated in all its parts but the getter does nothing different than returning just the identity reference.&lt;br /&gt;As summary, the problem is with the getter and the reason is simple: from user/coder perspective this may not make sense!&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;me.identity.name = "Andrea";&lt;br /&gt;&lt;br /&gt;alert(me); // WebReflection is 33&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In few words we are changing an object property, the one used as identity for the &lt;em&gt;me&lt;/em&gt; variable, leaving the instance of Person untouched ... and semantically speaking this looks wrong!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A Better Approach&lt;/h3&gt;If the setter aim is to update a state there will be only a well known amount of properties to re-assign before this status can be updated.&lt;br /&gt;In this example we would like to be sure that as soon as the identity has been set, the instance toString method will produce the expected result and without relying an external reference, the identity object itself.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// listOfNames and listOfAges are external Arrays&lt;br /&gt;// with same length&lt;br /&gt;for (var&lt;br /&gt;  identity = {},&lt;br /&gt;  population = [],&lt;br /&gt;  i = 0,&lt;br /&gt;  length = listOfNames.length;&lt;br /&gt;  i &lt; length; ++i&lt;br /&gt;) {&lt;br /&gt;  // reuse a single object to define identities&lt;br /&gt;  identity.name = listOfNames[i];&lt;br /&gt;  identity.age = listOfAges[i];&lt;br /&gt;  population[i] = new Person;&lt;br /&gt;  population[i].identity = identity;&lt;br /&gt;  // out of this loop we want that each &lt;br /&gt;  // instanceof Person prints out&lt;br /&gt;  // the right name and surname&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// we cannot do it lazily in the toString method ...&lt;br /&gt;// this will fail indeed&lt;br /&gt;Person.prototype.toString = function () {&lt;br /&gt;  return this._identity.name + " is " + this.identity._age;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Got it? It's basically what happens when we use an object to define a property, more properties, or to create inheriting from another one: properties and values are parsed and assigned at that moment, not after!&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var commonDefinition = {&lt;br /&gt;  enumerable: true,&lt;br /&gt;  writable: true,&lt;br /&gt;  configurable: false&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;var&lt;br /&gt;  name = (commonDefinition.value = "a"),&lt;br /&gt;  a = Object.defineProperty({}, "name", commonDefinition),&lt;br /&gt;  name = (commonDefinition.value = "b"),&lt;br /&gt;  b = Object.defineProperty({}, "name", commonDefinition)&lt;br /&gt;;&lt;br /&gt;alert([&lt;br /&gt;  a.name,  // "a"&lt;br /&gt;  b.name   // "b"&lt;br /&gt;]);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;As we can see if the property assignment would have been lazy the result of the latest alert would have been "b", "b" since the object used to define these properties has been recycled ... I hope you are still following ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A &lt;em&gt;Costy&lt;/em&gt; Solution&lt;/h3&gt;There is one approach we may consider in order to make this identity consistent ... the one that stores an identity with getters and setters.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// the magic identity configuration object&lt;br /&gt;Object.defineProperty(Person.prototype, "identity", {&lt;br /&gt;    set: function (identity) {&lt;br /&gt;        var self = this;&lt;br /&gt;&lt;br /&gt;        // do something meaningful&lt;br /&gt;        self._name = identity.name;&lt;br /&gt;        self._age = identity.age;&lt;br /&gt;&lt;br /&gt;        // store identity as fresh new object with bound behavior&lt;br /&gt;        this._identity = Object.defineProperties({}, {&lt;br /&gt;            name: {&lt;br /&gt;                get: function () {&lt;br /&gt;                    return self._name;&lt;br /&gt;                },&lt;br /&gt;                set: function (name) {&lt;br /&gt;                    self._name = name;&lt;br /&gt;                }&lt;br /&gt;            },&lt;br /&gt;            age: {&lt;br /&gt;                get: function () {&lt;br /&gt;                    return self._age;&lt;br /&gt;                },&lt;br /&gt;                set: function (age) {&lt;br /&gt;                    self._age = age;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        });&lt;br /&gt;    },&lt;br /&gt;    get: function () {&lt;br /&gt;        return this._identity;&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;What changed ? The fact that now we are able to pass through the instance and operate through the identity:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;&lt;br /&gt;me.identity.name = "Andrea";&lt;br /&gt;&lt;br /&gt;alert(me); // Andrea is 33&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Cool hu ? ... well, it could be better ... &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;A Faster Solution&lt;/h3&gt;If for each Person and each identity we have to create a fresh new object plus at least 4 functions, 2 for getters and 2 for relative setters, our memory will fill up so quickly that we won't be able to define any other person identity soon and here comes the fun part: use the knowledge gained by this pattern internally!&lt;br /&gt;Yes, what we could do to make things slightly better is to recycle the internal identity setter object definition in order to borrow maximum 4 functions rather than 4 extra per each Person instance ... sounds cool. uh?&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;function Person() {}&lt;br /&gt;Person.prototype.toString = function () {&lt;br /&gt;  return this._name + " is " + this._age;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;(function () {&lt;br /&gt;&lt;br /&gt;  var identityProperties = {&lt;br /&gt;    name: {&lt;br /&gt;      get: function () {&lt;br /&gt;        return this.reference._name;&lt;br /&gt;      },&lt;br /&gt;      set: function (name) {&lt;br /&gt;        this.reference._name = name;&lt;br /&gt;      },&lt;br /&gt;      configurable: true&lt;br /&gt;    },&lt;br /&gt;    age: {&lt;br /&gt;      get: function () {&lt;br /&gt;        return this.reference._age;&lt;br /&gt;      },&lt;br /&gt;      set: function (age) {&lt;br /&gt;        this.reference._age = age;&lt;br /&gt;      },&lt;br /&gt;      configurable: true&lt;br /&gt;    },&lt;br /&gt;    reference: {&lt;br /&gt;      value: null,&lt;br /&gt;      writable: true,&lt;br /&gt;      configurable: true&lt;br /&gt;    }&lt;br /&gt;  };&lt;br /&gt;&lt;br /&gt;  Object.defineProperty(Person.prototype, "identity", {&lt;br /&gt;    get: function () {&lt;br /&gt;      return this._identity;&lt;br /&gt;    },&lt;br /&gt;    set: function (identity) {&lt;br /&gt;      // something meaningful&lt;br /&gt;      this._name = identity.name;&lt;br /&gt;      this._age = identity.age;&lt;br /&gt;&lt;br /&gt;      // set the reference to the recycled object&lt;br /&gt;      identityProperties.reference.value = this;&lt;br /&gt;&lt;br /&gt;      // define the _identity property&lt;br /&gt;      if (!this._identity) {&lt;br /&gt;        Object.defineProperty(&lt;br /&gt;          this, "_identity", {value: {}}&lt;br /&gt;        );&lt;br /&gt;      }&lt;br /&gt;      Object.defineProperties(&lt;br /&gt;        this._identity,&lt;br /&gt;        identityProperties&lt;br /&gt;      );&lt;br /&gt;    }&lt;br /&gt;  });&lt;br /&gt;&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;var&lt;br /&gt;  identity = {},&lt;br /&gt;  a = new Person,&lt;br /&gt;  b = new Person&lt;br /&gt;;&lt;br /&gt;&lt;br /&gt;identity.name = "a";&lt;br /&gt;identity.age = 30;&lt;br /&gt;a.identity = identity;&lt;br /&gt;&lt;br /&gt;identity.name = "b";&lt;br /&gt;identity.age = 31;&lt;br /&gt;b.identity = identity;&lt;br /&gt;&lt;br /&gt;alert([&lt;br /&gt;  a,  // "a is 30"&lt;br /&gt;  b   // "b is 31"&lt;br /&gt;]);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So what we have there? A lazy &lt;em&gt;_identity&lt;/em&gt; definition, good for those scenario where some getter or setter may never been invoked, plus a smart recycled property definition through a single object descriptor, and performances boosted up N times per each instance since no multiple different functions are assigned per identity properties getters and setters and no extra objects are created runtime ... arf, arf .. are you still with me ?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;Some JS developer keep asking for standard ways to do these kind of crazy stuff without realizing that few other programming languages are that flexible as JavaScript is ... it's maybe not that simple to find better, optimized, in therms of both memory consumption and raw performances, patterns to cover &lt;em&gt;weird&lt;/em&gt; scenario but what we should appreciate is that with JS we almost have, always, a way to simulate something we did not even think about until the day before.&lt;br /&gt;Have fun with JS ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-2248627748932897780?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/2248627748932897780/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=2248627748932897780" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/2248627748932897780" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/2248627748932897780" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/m4z6eRLiw8s/on-complex-getters-and-setters.html" title="On Complex Getters And Setters" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>0</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/on-complex-getters-and-setters.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-8942219230640236570</id><published>2011-11-21T03:19:00.003+01:00</published><updated>2011-11-21T03:55:59.817+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="scroll" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="CSS" /><category scheme="http://www.blogger.com/atom/ns#" term="background" /><category scheme="http://www.blogger.com/atom/ns#" term="size" /><title type="text">Differential Background Scrolling</title><content type="html">A quick one about this technique quite common in Flash sites but rarely seen on Web.&lt;br /&gt;Have &lt;a href="http://3site.it/diffbg/"&gt;a look at the example&lt;/a&gt; first so you can understand what I am talking about ... got it ?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;What Is This About&lt;/h3&gt;Let's say we have a background, a big massive graphic background surely not suitable for mobile phones, due data roaming, but maybe cool for desktop and fast ADSL.&lt;br /&gt;The &lt;em&gt;background-size&lt;/em&gt; CSS property is able to let us decide if the image used as background should fit the whole element or only a portion of it.&lt;br /&gt;In this case the image should fit, by default, the whole height of the document with an auto width in order to let the browser adjust the scale.&lt;br /&gt;A differential scrolling is visible the moment we scroll the page ... please resize the window into a smaller one if you are in an HD monitor and start scrolling the page.&lt;br /&gt;At the very beginning, the default height of the image is 100%, as body background, and with some padding in order to let space for few important image parts such the header, with clouds and enough space for a H1 tag, and the bottom, with the stylish logo of &lt;a href="http://www.elderscrolls.com/skyrim/"&gt;this game from elderscrolls.com&lt;/a&gt;, the one which page inspired this little experiment. Bear in mind no code has been even read from that website ... I have seen the effect, I have used it many times ages ago via ActionScript, I decided to do something similar for most advanced browsers, and here is ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;pre class="code"&gt;&lt;br /&gt;(function (document) {&lt;br /&gt; // (C) WebReflection - Mit Style Licence&lt;br /&gt; var&lt;br /&gt;  ratio = .85, // 0 to 1 where 1 is 100%&lt;br /&gt;  &lt;br /&gt;  // shortcuts&lt;br /&gt;  styleSheets = document.styleSheets,&lt;br /&gt;  documentElement = document.documentElement,&lt;br /&gt;  ceil = Math.ceil,&lt;br /&gt;  scroll = "scroll",&lt;br /&gt;  scrollHeight = scroll + "Height",&lt;br /&gt;  scrollTop = scroll + "Top",&lt;br /&gt;  body, sHeight, sTop, y, last&lt;br /&gt; ;&lt;br /&gt; styleSheets = styleSheets[styleSheets.length - 1];&lt;br /&gt; // redefine the rule for the height&lt;br /&gt; styleSheets.insertRule(&lt;br /&gt;  "body{background-size:auto " + ceil(&lt;br /&gt;   ratio * 100&lt;br /&gt;  ) + "%;}",&lt;br /&gt;  styleSheets.cssRules.length&lt;br /&gt; );&lt;br /&gt; // get the rest of the ratio&lt;br /&gt; ratio = 1 - ratio;&lt;br /&gt; // attach a scroll listener&lt;br /&gt; addEventListener(scroll, function (e) {&lt;br /&gt;  if (body || (body = document.body)) {&lt;br /&gt;   sHeight =  documentElement[scrollHeight] ||&lt;br /&gt;      body[scrollHeight];&lt;br /&gt;   sTop =   documentElement[scrollTop] ||&lt;br /&gt;      body[scrollTop];&lt;br /&gt;   y = ceil(&lt;br /&gt;    ratio * sHeight * sTop / (sHeight - innerHeight)&lt;br /&gt;   );&lt;br /&gt;   // this avoid some redundant assignment&lt;br /&gt;   // hopefully creating less flicking effect&lt;br /&gt;   if (last != y) {&lt;br /&gt;    body.style.backgroundPosition = "center " + (last = y) + "px";&lt;br /&gt;   }&lt;br /&gt;  }&lt;br /&gt; }, false);&lt;br /&gt; // you may want to try this for Chrome Browsers&lt;br /&gt; //documentElement.style.WebkitTransform = "translateZ(0)";&lt;br /&gt;}(document));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Problem&lt;/h3&gt;Many of them ... to start with the fact this technique does not scale as showed in this example since for mobile phones, or generally speaking smaller screens, it does not make sense to use such big image: use media queries for this.&lt;br /&gt;Opera 12 is almost there but something goes terribly wrong during background reposition ... it's screwed up by N pixels even if the rest of the logic works and no error is shown on console.&lt;br /&gt;Firefox Nightly goes quite well but it is still flicking a bit while Safari, and even better WebKit Nightly, are the smoothest in this Mac.&lt;br /&gt;The disaster is Chrome Canary, which is not able to handle this background repositioning.&lt;br /&gt;You can see the effect if you scroll fast in both inspiration site and my experiment and, as commented out in the code, the only way to make it better is to force HW acceleration in the whole document 'cause in the body only the background looks broken ... it's really cool to see how DOM is able to mess up with GPUs, isn't it?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;Nothing much to add to this post, it was just a quick example over a cool effect but as it is, since ever, in this Web field, almost everything went terribly wrong :D&lt;br /&gt;Have fun with CSS and graceful JS enhancements!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-8942219230640236570?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/8942219230640236570/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=8942219230640236570" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8942219230640236570" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8942219230640236570" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/BmfM-vSoQWc/differential-background-scrolling.html" title="Differential Background Scrolling" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>4</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/differential-background-scrolling.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-642033905920782506</id><published>2011-11-12T13:02:00.014+01:00</published><updated>2011-11-12T17:23:33.777+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="patterns" /><title type="text">Few JavaScript Patterns</title><content type="html">Just to be clear and once again, JavaScript can emulate:&lt;ul&gt;&lt;li&gt;classes&lt;/li&gt;&lt;li&gt;public and public static methods or properties&lt;/li&gt;&lt;li&gt;private and private static methods or properties&lt;/li&gt;&lt;li&gt;public and private constants&lt;/li&gt;&lt;li&gt;protected methods&lt;/li&gt;&lt;li&gt;... you name it ...&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;pre class="code"&gt;// duck typing ( maybe all you need )&lt;br /&gt;var me = {name: "WebReflection"};&lt;br /&gt;&lt;br /&gt;// basic class&lt;br /&gt;function Person() {}&lt;br /&gt;Person.prototype.getName = function () {&lt;br /&gt;    return this.name;&lt;br /&gt;};&lt;br /&gt;Person.prototype.setName = function (name) {&lt;br /&gt;    this.name = name;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// module pattern + private properties / methods&lt;br /&gt;function Person(_name) {&lt;br /&gt;    function _getName() {&lt;br /&gt;        return _name;&lt;br /&gt;    }&lt;br /&gt;    return {&lt;br /&gt;        getName: function () {&lt;br /&gt;            // redundant, example only&lt;br /&gt;            return _getName();&lt;br /&gt;        },&lt;br /&gt;        setName: function (name) {&lt;br /&gt;            _name = name;&lt;br /&gt;        }&lt;br /&gt;    };&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// private shared methods via this&lt;br /&gt;var Person = (function () {&lt;br /&gt;    function Person() {}&lt;br /&gt;    function _getName () {&lt;br /&gt;        return this.name;&lt;br /&gt;    }&lt;br /&gt;    function _setName (name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;    Person.prototype.getName = function () {&lt;br /&gt;        return _getName.call(this);&lt;br /&gt;    };&lt;br /&gt;    Person.prototype.setName = function (name) {&lt;br /&gt;        _setName.call(this, name);&lt;br /&gt;    };&lt;br /&gt;    return Person;&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// private shared method Python style&lt;br /&gt;var Person = (function () {&lt;br /&gt;    function Person() {}&lt;br /&gt;    function _getName (self) {&lt;br /&gt;        return self.name;&lt;br /&gt;    }&lt;br /&gt;    function _setName (self, name) {&lt;br /&gt;        self.name = name;&lt;br /&gt;    }&lt;br /&gt;    Person.prototype.getName = function () {&lt;br /&gt;        return _getName(this);&lt;br /&gt;    };&lt;br /&gt;    Person.prototype.setName = function (name) {&lt;br /&gt;        _setName(this, name);&lt;br /&gt;    };&lt;br /&gt;    return Person;&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// public static&lt;br /&gt;function Person() {&lt;br /&gt;    Person.TOTAL++;&lt;br /&gt;}&lt;br /&gt;Person.TOTAL = 0;&lt;br /&gt;&lt;br /&gt;// private static / constant&lt;br /&gt;var Person = (function () {&lt;br /&gt;    var TOTAL = 0;&lt;br /&gt;    return function Person() {&lt;br /&gt;        TOTAL++;&lt;br /&gt;    };&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// public constant&lt;br /&gt;function Person() {}&lt;br /&gt;Object.defineProperty(Person, "RACE", {&lt;br /&gt;    writable: false,    // default&lt;br /&gt;    configurable: false,// default&lt;br /&gt;    enumerable: true,&lt;br /&gt;    value: "HUMAN"&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// public inherited constant&lt;br /&gt;function Person() {}&lt;br /&gt;Object.defineProperty(Person.prototype, "RACE", {&lt;br /&gt;    writable: false,    // default&lt;br /&gt;    configurable: false,// default&lt;br /&gt;    enumerable: true,&lt;br /&gt;    value: "HUMAN"&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// protected method&lt;br /&gt;function Person() {}&lt;br /&gt;Person.prototype.getName = function () {&lt;br /&gt;    return this instanceof Person ?&lt;br /&gt;        this.name :&lt;br /&gt;        throw "protected method violation"&lt;br /&gt;    ; &lt;br /&gt;};&lt;br /&gt;Person.prototype.setName = function (name) {&lt;br /&gt;    this instanceof Person ?&lt;br /&gt;        this.name = name :&lt;br /&gt;        throw "protected method violation"&lt;br /&gt;    ; &lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// generic protected methods&lt;br /&gt;Function.prototype.protectedVia = function (Class) {&lt;br /&gt;    var method = this;&lt;br /&gt;    Class || (Class = Object);&lt;br /&gt;    return function () {&lt;br /&gt;        if (this instanceof Class) {&lt;br /&gt;            return method.apply(this, arguments);&lt;br /&gt;        }&lt;br /&gt;        throw "protected method violation on " + (&lt;br /&gt;            Class.name || Class&lt;br /&gt;        );&lt;br /&gt;    };&lt;br /&gt;};&lt;br /&gt;function Person() {}&lt;br /&gt;Person.prototype.getName = function () {&lt;br /&gt;    return this.name;&lt;br /&gt;}.protectedVia(Person);&lt;br /&gt;Person.prototype.setName = function (name) {&lt;br /&gt;    this.name = name&lt;br /&gt;}.protectedVia(Person);&lt;br /&gt;&lt;br /&gt;// private shared variables&lt;br /&gt;function Person() {}&lt;br /&gt;Person.prototype.getName = function () {&lt;br /&gt;    return this.name;&lt;br /&gt;};&lt;br /&gt;(function (PersonPrototype) {&lt;br /&gt;    var changes = 0;&lt;br /&gt;    PersonPrototype.setName = function (name) {&lt;br /&gt;        changes++;&lt;br /&gt;        this.name = name;&lt;br /&gt;    };&lt;br /&gt;    PersonPrototype.howManyChangedName = function () {&lt;br /&gt;        return changes;&lt;br /&gt;    };&lt;br /&gt;}(Person.prototype));&lt;br /&gt;&lt;br /&gt;// getters / setters on public property&lt;br /&gt;var person = Object.defineProperty({}, "name", {&lt;br /&gt;    get: function () {&lt;br /&gt;        return this._name;&lt;br /&gt;    },&lt;br /&gt;    set: function (_name) {&lt;br /&gt;        this._name = _name;&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// getters setters on public property via prototype&lt;br /&gt;function Person() {}&lt;br /&gt;Object.defineProperty(Person.prototype, "name", {&lt;br /&gt;    get: function () {&lt;br /&gt;        return this._name;&lt;br /&gt;    },&lt;br /&gt;    set: function (_name) {&lt;br /&gt;        this._name = _name;&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// getters / setters on private property&lt;br /&gt;var person = Object.defineProperty({}, "name", (function () {&lt;br /&gt;    var _name;&lt;br /&gt;    return {&lt;br /&gt;        get: function () {&lt;br /&gt;            return _name;&lt;br /&gt;        },&lt;br /&gt;        set: function (name) {&lt;br /&gt;            _name = name;&lt;br /&gt;        }&lt;br /&gt;    };&lt;br /&gt;}()));&lt;br /&gt;&lt;br /&gt;// singleton&lt;br /&gt;var me = {name: "WebReflection"};&lt;br /&gt;&lt;br /&gt;// singleton via anonymous __proto__&lt;br /&gt;// plus private properties&lt;br /&gt;var me = new function () {&lt;br /&gt;    var _name;&lt;br /&gt;    this.getName = function () {&lt;br /&gt;        return _name;&lt;br /&gt;    };&lt;br /&gt;    this.setName = function (name) {&lt;br /&gt;        _name = name;&lt;br /&gt;    };&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;// generic singleton cross browser&lt;br /&gt;Function.prototype.singleton = (function () {&lt;br /&gt;    function anonymous(){};&lt;br /&gt;    function create(Class, args) {&lt;br /&gt;        anonymous.prototype = Class.prototype;&lt;br /&gt;        Class.apply(&lt;br /&gt;            Class.__singleton__ = new anonymous,&lt;br /&gt;            args&lt;br /&gt;        );&lt;br /&gt;        return Class.__singleton__;&lt;br /&gt;    }&lt;br /&gt;    return function singleton() {&lt;br /&gt;        return this.__singleton__ || create(this, arguments);&lt;br /&gt;    };&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// generic singleton ES5&lt;br /&gt;Function.prototype.singleton = (function () {&lt;br /&gt;    function create(Class, args) {&lt;br /&gt;        Class.apply(&lt;br /&gt;            Class.__singleton__ = Object.create(&lt;br /&gt;                Class.prototype&lt;br /&gt;            ), args&lt;br /&gt;        );&lt;br /&gt;        return Class.__singleton__;&lt;br /&gt;    }&lt;br /&gt;    return function singleton() {&lt;br /&gt;        returh this.__singleton__ || create(this, arguments);&lt;br /&gt;    };&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// per function private singleton&lt;br /&gt;var Person = (function () {&lt;br /&gt;    var instance;&lt;br /&gt;    return function Person () {&lt;br /&gt;        return instance || (instance = this);&lt;br /&gt;        // or ... ot be more than sure ...&lt;br /&gt;        return instance || (&lt;br /&gt;            (instance = true) &amp;&amp; // avoid infinite recursion&lt;br /&gt;            (instance = new Person)&lt;br /&gt;        );&lt;br /&gt;    };&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// generic factory&lt;br /&gt;Function.prototype.factory = (function () {&lt;br /&gt;    function anonymous() {};&lt;br /&gt;    return function factory() {&lt;br /&gt;        anonymous.prototype = this.prototype;&lt;br /&gt;        var instance = new anonymous;&lt;br /&gt;        this.apply(instance, arguments);&lt;br /&gt;        return instance;&lt;br /&gt;    };&lt;br /&gt;}());&lt;br /&gt;&lt;br /&gt;// generic factory ES5 + ruby style&lt;br /&gt;Function.prototype.new = function factory() {&lt;br /&gt;    var instance = Object.create(this.prototype);&lt;br /&gt;    this.apply(instance, arguments);&lt;br /&gt;    return instance;&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-642033905920782506?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/642033905920782506/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=642033905920782506" title="10 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/642033905920782506" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/642033905920782506" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/dzvjcJ8A8HY/few-javascript-patterns.html" title="Few JavaScript Patterns" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>10</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/few-javascript-patterns.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-6267040038417456704</id><published>2011-11-08T23:33:00.007+01:00</published><updated>2011-11-09T08:45:45.704+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="function" /><category scheme="http://www.blogger.com/atom/ns#" term="notification" /><category scheme="http://www.blogger.com/atom/ns#" term="monitor" /><category scheme="http://www.blogger.com/atom/ns#" term="Callback" /><category scheme="http://www.blogger.com/atom/ns#" term="test" /><title type="text">Function.prototype.notifier</title><content type="html">There are way too many ways to &lt;em&gt;stub&lt;/em&gt; functions or methods, but at the end of the day all we want to know is always the same:&lt;ul&gt;&lt;li&gt;has that function been invoked ?&lt;/li&gt;&lt;li&gt;has that function received the expected context ?&lt;/li&gt;&lt;li&gt;which argument has been passed to that function ?&lt;/li&gt;&lt;li&gt;what was the output of the function ?&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;strong&gt;Update&lt;/strong&gt; thanks to &lt;a href="http://twitter.com/bga_"&gt;@bga_&lt;/a&gt; hint about the output property in after notification, it made perfect sense&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Concept&lt;/h3&gt;For fun and no profit I have created a prototype which aim is to bring a &lt;strong&gt;DOM like interface to any sort of function or method&lt;/strong&gt; in order to monitor its lifecycle:&lt;ul&gt;&lt;li&gt;the &lt;em&gt;"before"&lt;/em&gt; event, able to &lt;em&gt;preventDefault()&lt;/em&gt; and avoid the original function call at all&lt;/li&gt;&lt;li&gt;the &lt;em&gt;"after"&lt;/em&gt; event, in order to understand if the function did those expected changes to the environment or to a generic input object, or simply to analyze the output of the previous call&lt;/li&gt;&lt;li&gt;the &lt;em&gt;"error"&lt;/em&gt; event, in case we want to be notified if something went wrong during function execution&lt;/li&gt;&lt;li&gt;the &lt;em&gt;"handlererror"&lt;/em&gt; event, just in case we are the cause of an error while we are monitoring the original function&lt;/li&gt;&lt;/ul&gt;The reason I have chosen an &lt;em&gt;addEventListener&lt;/em&gt; like interface, called in this case &lt;em&gt;addListener&lt;/em&gt;, is simple: JavaScript works pretty well with event driven applications so what else could be better than an event driven approach?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Basic Example&lt;/h3&gt;&lt;pre class="code"&gt;&lt;br /&gt;var nFromCharcode = String.fromCharCode.notifier({&lt;br /&gt;    before: function (e) {&lt;br /&gt;        if (e.arguments.length &amp;gt; 2048) {&lt;br /&gt;            throw "too many arguments";&lt;br /&gt;            e.preventDefault(); // won't even try to execute it&lt;br /&gt;        }&lt;br /&gt;        // in case you want to remove this listener ... &lt;br /&gt;        e.notifier.removeListener("before", e.handler);&lt;br /&gt;    },&lt;br /&gt;    after: function (e) {&lt;br /&gt;        if (e.output !== "PQR") {&lt;br /&gt;            throw "expected PQR got " + e.output + " instead";&lt;br /&gt;        }&lt;br /&gt;    },&lt;br /&gt;    handlererror: function (e) {&lt;br /&gt;        testFramework.failBecause("" + e.error);&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// run the test ...&lt;br /&gt;nFromCharcode(80, 81, 82); // "PQR"&lt;br /&gt;nFromCharcode.apply(null, arrayOf2049Codes); // testFramework will fail&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The notifier itself is a function, precisely the original function wrapper with enriched API in order to monitor almost every aspect of a method or a function.&lt;br /&gt;The event object passed through each listener has these properties:&lt;ul&gt;&lt;li&gt;notifier: the object create to monitor the function and notify all listeners&lt;/li&gt;&lt;li&gt;handler: the current handler to make the notifier remove listener easier&lt;/li&gt;&lt;li&gt;callback: the original function that has been wrapped by the notifier&lt;/li&gt;&lt;li&gt;type: the event type such before, error, after, handlererror&lt;/li&gt;&lt;li&gt;arguments: passed arguments transformed already into array&lt;/li&gt;&lt;li&gt;context: the "this" reference used as callback context&lt;/li&gt;&lt;li&gt;error: the optional error object for events error and handlererror&lt;/li&gt;&lt;li&gt;preventDefault: the method able to avoid function execution if called in the before listener&lt;/li&gt;&lt;li&gt;output: assigned only during &lt;em&gt;"after"&lt;/em&gt; notification and if no error occurred, handy to compare expected results&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;I guess there is really nothing else we could possibly know about a notifier, and its callback, lifecycle, what do you think?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Code&lt;/h3&gt;&lt;br /&gt;&lt;script src="https://gist.github.com/1345695.js?file=Function.prototype.notifier.js"&gt;&lt;/script&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;&lt;br /&gt;I have also a &lt;a href="https://gist.github.com/1349511"&gt;full test coverage&lt;/a&gt; for this notifier and I hope someone will use it and will come back to provide some feedback, cheers!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-6267040038417456704?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/6267040038417456704/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=6267040038417456704" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/6267040038417456704" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/6267040038417456704" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/hZz3LLNK6SM/functionprototypenotifier.html" title="Function.prototype.notifier" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>9</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/11/functionprototypenotifier.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-7923066140429273468</id><published>2011-10-31T20:52:00.009+01:00</published><updated>2011-10-31T22:53:40.983+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="Sniff" /><category scheme="http://www.blogger.com/atom/ns#" term="User" /><category scheme="http://www.blogger.com/atom/ns#" term="Agent" /><title type="text">On User Agent Sniffing</title><content type="html">Oh well, who was following me on twitter today is already bored about this topic (I guess) but probably other developers would like to read this too so ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;What Is UA Sniffing&lt;/h3&gt;UserAgent sniffing means that a generic software is relying into a generic string representation of the underlying system. The User Agent is basically considered a unique identifier of "&lt;em&gt;the current software or hardware that is running the app&lt;/em&gt;".&lt;br /&gt;In native applications world UA could be simply the platform name ... where if it's "&lt;i&gt;Darwin&lt;/i&gt;" it means we are in a Mac platform, while if it's Win32 or any other "&lt;i&gt;/^Win.*$/&lt;/i&gt;" environment, the app reacts, compile, execute, as if it is in a Windows machine ... and so on with Linux and relative distributions.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The "Native" Software Behavior&lt;/h3&gt;If you have an hybrid solution, example those solutions not allowed anymore but called Hachintosh not long time ago, your machine has most likely Windows Starter capable Hardware but it's running compiled Objective-C language. How reliable you think this machine is? Every software will consider it a Mac Hardware capable machine.&lt;br /&gt;Should these applications optimize for &lt;strong&gt;non Mac&lt;/strong&gt; hardware? I don't think so .... I mean, that machine was not classified in first place as Mac capable machine, it was the user/hacker that decided to do something "&lt;i&gt;nasty&lt;/i&gt;" so that if something does not work ... who does really care?&lt;br /&gt;Do you really want to provide support for that "&lt;i&gt;random machine in the system&lt;/i&gt;"?&lt;br /&gt;I still don't think so ... also, if you know performances and provided hardware has reached certain levels in that environment, do you even want to waste time optimizing things for a Netbook user?&lt;br /&gt;I think reality is that you just create software for the target, or those targets, you want to support and nothing else, isn't it? ... but of course new unexpected comers are, hopefully, welcome ...&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Old Web Behavior&lt;/h3&gt;UA sniffing has historically been a bad practice in the world wide web (internet). At the very beginning there was only a major and supported browser, Internet Explorer, and this had something like 80% or more of market share. All developers, browsers vendors, and users with a different browser where most likely redirected into a page that was saying something like: "&lt;i&gt;Your browser is not supported. Please come back with IE!&lt;/i&gt;"&lt;br /&gt;Even worst, this was happening on the server side level ... "&lt;i&gt;why that&lt;/i&gt;"? Because websites where created, and tested, entirely in Internet Explorer as unique target for any sort of online business.&lt;br /&gt;Was that a good choice? Today we can say it wasn't but back at that time it was making sense on business level.&lt;br /&gt;How many apps we know that work only on Windows or only on Mac? Many of them, and we are talking about only two platforms.&lt;br /&gt;At least at that point we had a server side degradation into a non service completely useless for not targeted browsers but ... hey, that was their business, and if they wanted to use &lt;em&gt;ActiveXObject&lt;/em&gt; because many things where not possible in other browsers, how can we blame these companies? "&lt;em&gt;Everywhere or nothing&lt;/em&gt;"? A nice utopia that won't bring you that far in real world .... nothing, I repeat, nothing works 100% as expected everywhere.&lt;br /&gt;The dream is to reach that point but stories like Java, .NET VS Mono, Python itself, and of course JavaScript, should ring a little bell in our developers mind ... we can still go close though, at least on the Web side!&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Modern Web Behavior&lt;/h3&gt;Recently things changed quite a lot on web side and only few companies are redirecting via server side User Agent sniffing. We have now something called &lt;strong&gt;runtime features detections&lt;/strong&gt;, something that supposes to test indeed runtime browser capabilities and understand, still runtime, if the browser should be redirected or not into a hopefully meaningful fallback or degraded service.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Features Detections Good Because&lt;/h3&gt;Well, specially because the browsers fragmentation is massive, FD can tell us what we need from the current one, without penalizing in advance anybody.&lt;br /&gt;The potential redirection or message only if necessary, informing the user his/her browser is not capable of features required to grant a decent experience in the current online application/service.&lt;br /&gt;FDs are also widely suggested for future compatibility with new browsers we may not be able to test, or recognize, with any sort of list present in our server side logic, the one that is not directly able to understand if the current browser may run the application/service or not.&lt;br /&gt;Of course to be automatically compatible with newer browsers is both business value, as "&lt;i&gt;there before we know&lt;/i&gt;", and simplified maintenance of the application/logic itself, since if it was working accordingly with certain features, of course it's going to work accordingly with newer or improved features we need.&lt;br /&gt;As summary, runtime features detections can be extremely valuable for our business ... but&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Features Detections Bad Because&lt;/h3&gt;Not sure I have to tell you that the first browser with disabled JavaScript support will fail all detections even if theoretically capable ... but lets ignore these cases for now, right?&lt;br /&gt;Well, it's kinda right, 'cause we may have detected browsers with JS disabled already in the server side thanks to user headers or specific agent ... should I mention Lynx browser ? Try to detect that one via JavaScript ... &lt;br /&gt;Back to "&lt;i&gt;real world cases&lt;/i&gt;", all techniques used today for runtime features detections are kinda weak ... or better, extremely weak!&lt;br /&gt;I give you an example:&lt;pre class="code"&gt;&lt;br /&gt;// the "shimmable"&lt;br /&gt;if (!("forEach" in []) || !Array.prototype.forEach) {&lt;br /&gt;    // you wish this gonna fix everything, uh? ... &lt;br /&gt;    Array.prototype.forEach = function () { ... };&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// the unshimmable&lt;br /&gt;if (!document.createElement("canvas").getContext("2d")) {&lt;br /&gt;    // no canvas support ... you wish to know here ...&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Not because I want to disappoint you but you gonna be potentially wrong in both cases ... why that?&lt;br /&gt;Even if &lt;em&gt;Array.prototype.forEach&lt;/em&gt; is exposed and this is the only Array extra you need, &lt;a href="http://code.google.com/p/chromium/issues/detail?id=100702&amp;thanks=100702&amp;ts=1318946276"&gt;things may go wrong&lt;/a&gt;. As example, the first shim will never be executed in a case where &lt;i&gt;"forEach" in []&lt;/i&gt; is true, even if that shim would have solved our problem.&lt;br /&gt;That bug I have filed few days ago demonstrated that we cannot really trust the fact a method is somewhere since we should write a whole test suite for a single method in order to be sure everything will work as expected &lt;strong&gt;OR&lt;/strong&gt; we gonna write unit, acceptance, integration, and functional tests to be sure that a bloody browser works as expected in our application.&lt;br /&gt;Same is valid for classic canvas capability ... once we have that, do we really test that every method works as expected? And if we need only a single method out of the canvas, how can we understand that method is there and is working as expected without involving, for the single test, part of the API that may not work but even though we don't care since we need only the very first one?&lt;br /&gt;I am talking about &lt;em&gt;drawImage&lt;/em&gt;, as example, in old Symbian browsers, where canvas is exposed but drawImage does not visually draw anything on the element ... nice, isn't it?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;You Cannot Detect Everything Runtime&lt;/h3&gt; ... or better, if you do, most likely any user has to wait few minutes before the &lt;a href="http://test262.ecmascript.org/#"&gt;whole&lt;/a&gt; &lt;a href="http://acid3.acidtests.org/"&gt;test&lt;/a&gt; suite becomes green, specially in mobile browsers where any of these tests take ages burning battery life, CPU clocks, RAM, and everything else before the page can be even visualized since we would like to redirect the user before he can see the experience is already broken, isn't it?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;IT Is Not Black Or White&lt;/h3&gt;... you think so? I think IT is more about "&lt;em&gt;what's the most convenient solution for this problem&lt;/em&gt;", assuming there is, generally speaking, no best solution to a specific problem, since every problem can be solved differently and in a better way, accordingly with the surrounding environment.&lt;br /&gt;So how do we brainstorm all these possible edge cases that cannot obviously be solved runtime in a meaningful, reliable way?&lt;br /&gt;&lt;blockquote&gt;&lt;br /&gt;I want provide same experience to as many users as possible but thanks to my tests I have already found user X, Y, and Z, that cannot possibly be compatible with the application/service I am trying to offer.&lt;br /&gt;If I detect runtime everything I need for my app, assuming this is possible, every browser I already know has no problems there will be penalized for non updated, low market share, problematic alternatives.&lt;br /&gt;If I sniff the User Agent with a list of browsers I already know I cannot possibly support due lack of unshimmable features, how faster will be on startup time every other browser I am interested on?&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Best Solution Now&lt;/h3&gt;If you ask me, today and specially on mobile side, we have 3 categories of browsers:&lt;ol&gt;&lt;li&gt;those almost there&lt;/li&gt;&lt;li&gt;those not there yet&lt;/li&gt;&lt;li&gt;those will never be there&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;In a business logic you don't even want to waste time for the third category ... "&lt;em&gt;money for nothing&lt;/em&gt;", as &lt;a href="http://en.wikipedia.org/wiki/Mark_Knopfler"&gt;Mark Knopfler&lt;/a&gt; would say.&lt;br /&gt;You also do not want to penalize most interesting browsers categories due massive amount, size and computation logic speaking, of features detections ... I mean, we know those browsers are crap and a minority, the server side User Agent sniffing would be the most suitable solution ever providing any sort of possible fallback or info, if there is no budget for that fallback.&lt;br /&gt;But what about the second category?&lt;br /&gt;Well, it depends ... if the second category has a decent market share you may try to support it and let it pass all your tests but at which price?&lt;br /&gt;If the whole application has to be different for that single browser, and it shares less than 10% of the global market share, reflected into 1% of your users, do you really want to spend all possible effort to make it work?&lt;br /&gt;I would say it makes sense only if this browser has few, shimmable, problems ... otherwise the best place for this browser would be directly the server side, don't you think?&lt;br /&gt;About the first category ... well, it's still about guessing, hoping, praying, that things go as expected but at least for these browsers we can run all our tests against them and be sure that things are at least similar.&lt;br /&gt;I am not talking about pixel perfection, that is bad as well in most of the Web related cases, I am talking about providing a decent experience in your Web application/software/page that strongly relies into JavaScript and that without it cannot possibly work.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;Few things must be re-considered in the current Web era. Kangax already explained that &lt;a href="http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/"&gt;things today are different&lt;/a&gt;, regarding native prototype pollutions and specially via &lt;em&gt;Object.defineProperty&lt;/em&gt; and the non enumerable flag but for years we have been all convinced that extending those proto was absolutely something to avoid.&lt;br /&gt;Well, as I agree with Juriy about latter topic, I am still a problem solver that does not exclude any possibility, including User Agent sniffing, when it comes to &lt;strong&gt;solve a real world problem&lt;/strong&gt;, rather than have fantasies about ideals that unfortunately do not reflect reality on our daily basis web development role.&lt;br /&gt;&lt;br /&gt;Just think about it ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-7923066140429273468?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/7923066140429273468/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=7923066140429273468" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7923066140429273468" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/7923066140429273468" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/4V8zXNifDpU/on-user-agent-sniffing.html" title="On User Agent Sniffing" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>0</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/10/on-user-agent-sniffing.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-8781151831894657341</id><published>2011-10-25T21:51:00.003+02:00</published><updated>2011-10-25T22:00:09.733+02:00</updated><title type="text">JS getCSSPropertyName Function</title><content type="html">I was re-checking &lt;a href="http://twitter.com/LeaVerou"&gt;@LeaVerou&lt;/a&gt; talk at jsconf.eu looking forward to see mine there too to understand how to improve and specially what the hell I have said for 45 minutes :D&lt;br /&gt;&lt;br /&gt;Lea made many valid points in &lt;a href="http://blip.tv/jsconfeu/lea-verou-polyfilling-the-gaps-5668145"&gt;her presentation&lt;/a&gt; but as is for &lt;em&gt;supports.property&lt;/em&gt; case, you never want to go too deep into a single point of your talk so ... here I come.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;getCSSPropertyName Function&lt;/h3&gt;This function aim is to understand if the current browser supports a generic CSS property. If property is supported, the whole name included prefix will be returned.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var getCSSPropertyName = (function () {&lt;br /&gt;    var&lt;br /&gt;        prefixes = ["", "-webkit-", "-moz-", "-ms-", "-o-", "-khtml-"],&lt;br /&gt;        dummy = document.createElement("_"),&lt;br /&gt;        style = dummy.style,&lt;br /&gt;        cache = {},&lt;br /&gt;        length = prefixes.length,&lt;br /&gt;        i = 0,&lt;br /&gt;        pre&lt;br /&gt;    ;&lt;br /&gt;    function testThat(name) {&lt;br /&gt;        for (i = 0; i &amp;lt; length; ++i) {&lt;br /&gt;            pre = prefixes[i] + name;&lt;br /&gt;            if (&lt;br /&gt;                pre in style || (&lt;br /&gt;                    (style.cssText = pre + ":inherit") &amp;&amp;&lt;br /&gt;                    style.getPropertyValue(pre)&lt;br /&gt;                )&lt;br /&gt;            ) return pre;&lt;br /&gt;        }&lt;br /&gt;        return null;&lt;br /&gt;    }&lt;br /&gt;    return function getCSSPropertyName(name) {&lt;br /&gt;        return cache.hasOwnProperty(name) ?&lt;br /&gt;            cache[name] :&lt;br /&gt;            cache[name] = testThat(name)&lt;br /&gt;        ;&lt;br /&gt;    };&lt;br /&gt;}());&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The function returns a string or null, if no property has been found.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;// enable HW acceleration&lt;br /&gt;var cssPropertyName = getCSSPropertyName("transform");&lt;br /&gt;if (cssPropertyName != null) {&lt;br /&gt;    node.style.cssText += cssPropertyName + ":translate3d(0,0,0);";&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Please feel free to test this function and let me know if something went wrong, thanks ;-)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-8781151831894657341?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/8781151831894657341/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=8781151831894657341" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8781151831894657341" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8781151831894657341" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/XNpgUf77fdA/js-getcsspropertyname-function.html" title="JS getCSSPropertyName Function" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>5</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/10/js-getcsspropertyname-function.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-5623774948951873390</id><published>2011-10-20T21:25:00.006+02:00</published><updated>2011-10-20T21:32:05.381+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="wru" /><category scheme="http://www.blogger.com/atom/ns#" term="Unit Test" /><category scheme="http://www.blogger.com/atom/ns#" term="JavaScirpt" /><category scheme="http://www.blogger.com/atom/ns#" term="easy" /><title type="text">My BerlinJS Slides</title><content type="html">It was a great event today at &lt;a href="http://twitter.com/co_up"&gt;@co_up&lt;/a&gt; in &lt;a href="http://twitter.com/berlinjs"&gt;@berlinjs&lt;/a&gt; meet-up and &lt;a href="http://www.3site.eu/wru.pdf"&gt;here are my sides&lt;/a&gt; about &lt;strong&gt;wru&lt;/strong&gt; which accordingly with today meeting means &lt;em&gt;where are you&lt;/em&gt;, directly out of SMS syntax.&lt;br /&gt;&lt;br /&gt;Enjoy ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-5623774948951873390?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/5623774948951873390/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=5623774948951873390" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/5623774948951873390" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/5623774948951873390" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/Ql4hIuiBDk4/jsberlin-slides.html" title="My BerlinJS Slides" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>5</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/10/jsberlin-slides.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-8349619330375041121</id><published>2011-10-20T07:32:00.002+02:00</published><updated>2011-10-20T07:51:35.157+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="fun" /><category scheme="http://www.blogger.com/atom/ns#" term="DOM" /><title type="text">Playing With DOM And ES5</title><content type="html">A quick fun post about "&lt;i&gt;how would you solve this real world problem&lt;/i&gt;".&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Problem&lt;/h3&gt;Given a generic array of strings, create an unordered list of items where each item contains the text of the relative array index without creating a singe leak or reference during the whole procedure.&lt;br /&gt;As plus, make each item in the list clickable so that an &lt;i&gt;alert&lt;/i&gt; with current text content occur once clicked.&lt;br /&gt;&lt;br /&gt;The assumption is that we are in a standard W3C environment with ES5+ support.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Reason&lt;/h3&gt;I think is one of the most common tasks in Ajax world. We receive an array with some info, we want to display this info to the user and we want to react once the user interact with the list.&lt;br /&gt;If we manage to avoid references we are safer about leaks. If we manage to optimize the procedure, we are also safe about memory consumption over a simplified DOM logic ... &lt;br /&gt;How would you solve this ? Give it a try, then come back for my solution.&lt;br /&gt;&lt;br /&gt;&lt;img src="http://www.3site.eu/images/monkey-on-computer.jpg" /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Solution&lt;/h3&gt;Here mine:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;document.body.appendChild(&lt;br /&gt;  /* input */["a","b","c"].map(&lt;br /&gt;    function (s, i) {&lt;br /&gt;      this.appendChild(&lt;br /&gt;        document.createElement("li")&lt;br /&gt;      ).textContent = s;&lt;br /&gt;      return this;&lt;br /&gt;    },&lt;br /&gt;    document.createElement("ul")&lt;br /&gt;  )[0]&lt;br /&gt;).addEventListener(&lt;br /&gt;  "click",&lt;br /&gt;  function (e) {&lt;br /&gt;    if (e.target.nodeName === "LI") {&lt;br /&gt;      alert(e.target.textContent);&lt;br /&gt;    }&lt;br /&gt;  },&lt;br /&gt;  false&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Did you solve it the same way ? :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-8349619330375041121?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/8349619330375041121/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=8349619330375041121" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8349619330375041121" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/8349619330375041121" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/fGLX5FrWhWI/playing-with-dom-and-es5.html" title="Playing With DOM And ES5" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>9</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/10/playing-with-dom-and-es5.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-6475054649811876136</id><published>2011-10-19T01:05:00.007+02:00</published><updated>2011-10-19T01:58:19.570+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Object" /><category scheme="http://www.blogger.com/atom/ns#" term="configurable" /><category scheme="http://www.blogger.com/atom/ns#" term="enumerable" /><category scheme="http://www.blogger.com/atom/ns#" term="writable" /><category scheme="http://www.blogger.com/atom/ns#" term="defineProperty" /><title type="text">Do You Really Know Object.defineProperty ?</title><content type="html">I am talking about &lt;em&gt;enumerable&lt;/em&gt;, &lt;em&gt;configurable&lt;/em&gt;, and &lt;em&gt;writable&lt;/em&gt; properties of a generic property descriptor.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;enumerable&lt;/h3&gt;most likely the only one we all expect: if false, a classic &lt;em&gt;for/in&lt;/em&gt; loop will not expose the property, otherwise it will. &lt;em&gt;enumerable&lt;/em&gt; is false by default.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;writable&lt;/h3&gt;just a bit more tricky than we think. Nowadays, if a property is defined as non writable, no error will occur the moment we'll try to change this property:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var o = {};&lt;br /&gt;Object.defineProperty(o, "test", {&lt;br /&gt;  writable: false,&lt;br /&gt;  value: 123&lt;br /&gt;});&lt;br /&gt;o.test; // 123&lt;br /&gt;o.test = 456; // no error at all&lt;br /&gt;o.test; // 123&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So the property is not writable but nothing happens unless we try to redefine that property.&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;Object.defineProperty(o, "test", {&lt;br /&gt;  writable: false,&lt;br /&gt;  value: 456&lt;br /&gt;});&lt;br /&gt;// throws&lt;br /&gt;// Attempting to change value of a readonly property.&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Got it ? Every time we would like to set a property of an unknown object, or one shared in an environment we don't trust, either we use a &lt;em&gt;try/catch&lt;/em&gt; plus double check, or we must be sure that &lt;em&gt;Object.getOwnPropertyDescriptor(o, "test").writable&lt;/em&gt; is &lt;strong&gt;true&lt;/strong&gt;.&lt;br /&gt;&lt;em&gt;writable&lt;/em&gt; is false by default too.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;configurable&lt;/h3&gt;This is the wicked one ... what would you expect from configurable ?&lt;ul&gt;&lt;li&gt;I cannot set a different type of value&lt;/li&gt;&lt;li&gt;I cannot re-configure the descriptor&lt;/li&gt;&lt;/ul&gt;&lt;strong&gt;Fail in both cases&lt;/strong&gt; since things are a bit different on real world. Take this example:&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;var o = Object.defineProperty({}, "test", {&lt;br /&gt;  enumerable: false,&lt;br /&gt;  writable: true,&lt;br /&gt;  configurable: false, // note, it's false&lt;br /&gt;  value: 123&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Do you think this would be possible ?&lt;br /&gt;&lt;pre class="code"&gt;&lt;br /&gt;Object.defineProperty(o, "test", {&lt;br /&gt;  enumerable: false,&lt;br /&gt;  writable: false, // note, this is false only now&lt;br /&gt;  configurable: false,&lt;br /&gt;  value: "456" // note, type and value is different&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// did I re-configure it ?&lt;br /&gt;o.test === "456"; // true !!!&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Good, so a variable that is writable can be reconfigured on writable attribute and on its type.&lt;br /&gt;The only attribute that cannot be changed, once flagged as configurable and bear in mind that &lt;em&gt;false&lt;/em&gt; is the default, is &lt;em&gt;configurable&lt;/em&gt; itself plus &lt;em&gt;enumerable&lt;/em&gt;.&lt;br /&gt;Also &lt;em&gt;writable&lt;/em&gt; is false by default.&lt;br /&gt;This inconsistency about &lt;em&gt;configurable&lt;/em&gt; seems to be pretty much cross platform and probably meant ... why ?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Brainstorming&lt;/h3&gt;If I can't change the value the descriptor must be &lt;em&gt;configurable&lt;/em&gt; at least on &lt;em&gt;writable&lt;/em&gt; property ... no wait, if I can set the value as not &lt;em&gt;writable&lt;/em&gt; then &lt;em&gt;configurable&lt;/em&gt; should be set as false otherwise it will loose its own meaning ... no, wait ... &lt;br /&gt;&lt;br /&gt;&lt;h3&gt;How It Is&lt;/h3&gt;&lt;em&gt;writable&lt;/em&gt; is the exception that confirms the rule. If &lt;em&gt;true&lt;/em&gt;, writable can always be configurable while if &lt;em&gt;false&lt;/em&gt;, &lt;em&gt;writable&lt;/em&gt; becomes automatically &lt;em&gt;not configurable&lt;/em&gt; and the same is true for both &lt;em&gt;get&lt;/em&gt; and &lt;em&gt;set&lt;/em&gt; properties ... these acts as &lt;em&gt;writable: false&lt;/em&gt; no matters how &lt;em&gt;configurble&lt;/em&gt; is set.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;How Is It If We Do Not Define&lt;/h3&gt;&lt;pre class="code"&gt;&lt;br /&gt;// simple object&lt;br /&gt;var o = {};&lt;br /&gt;&lt;br /&gt;// simple assignment&lt;br /&gt;o.test = 123;&lt;br /&gt;&lt;br /&gt;// equivalent in Object.defineProperty world&lt;br /&gt;Object.defineProperty(o, "test", {&lt;br /&gt;  configurable: true,&lt;br /&gt;  writable: true,&lt;br /&gt;  enumerable: true,&lt;br /&gt;  value: 123&lt;br /&gt;});&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Thanks to &lt;a href="http://twitter.com/jdalton"&gt;@jdalton&lt;/a&gt; to point few hints out.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;As Summary&lt;/h3&gt;The &lt;em&gt;configurable&lt;/em&gt; property works as expected with &lt;em&gt;configurable&lt;/em&gt; itself and &lt;strong&gt;only&lt;/strong&gt; with &lt;em&gt;enumerable&lt;/em&gt; one.&lt;br /&gt;If we think that &lt;em&gt;writable&lt;/em&gt; has anything to do with both of them we are wrong ... at least now we know.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-6475054649811876136?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/6475054649811876136/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=6475054649811876136" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/6475054649811876136" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/6475054649811876136" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/4beQOEG2Tk4/do-you-really-know-objectdefineproperty.html" title="Do You Really Know Object.defineProperty ?" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>4</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/10/do-you-really-know-objectdefineproperty.html</feedburner:origLink></entry><entry><id>tag:blogger.com,1999:blog-34454975.post-2889867172226370799</id><published>2011-10-16T13:49:00.003+02:00</published><updated>2011-10-16T14:24:51.563+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><category scheme="http://www.blogger.com/atom/ns#" term="programming" /><category scheme="http://www.blogger.com/atom/ns#" term="LLVM" /><category scheme="http://www.blogger.com/atom/ns#" term="languages" /><category scheme="http://www.blogger.com/atom/ns#" term="scripting" /><title type="text">The Missing Tool In Scripting World</title><content type="html">Few days ago I was having beers with &lt;a href="http://twitter.com/aadsm"&gt;@aadsm&lt;/a&gt; and &lt;a href="http://twitter.com/sleistner"&gt;@sleistner&lt;/a&gt; and we were talking about languages and, of course, JavaScript too.&lt;br /&gt;That night I have realized there is a missing process, or better tool, that could open new doors for JavaScript world.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Runtime Nightmare&lt;/h3&gt;The main difference between scripting languages and statically typed one is the inability to pre optimize or pre compile the code before it's actually executed.&lt;br /&gt;Engineers from different companies are trying on daily basis to perform this optimization at runtime, or better Just In Time, but believe me that's not easy task, specially with such highly dynamic language as JavaScript is.&lt;br /&gt;Even worst task is the tracing option: at runtime each reference is tracked and if its type does not change during its lifecycle, the code could be compiled as native one.&lt;br /&gt;The moment a type, an object structure, or a property changes, the tracer has to compile twice or split the optimizations up to N exponential changed performed in a single loop so that this tracer has to be smart enough to understand when it's actually worth it to perform such optimization, or when it's time to drop everything and optimize only sub tasks via JIT.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Static Pros And Cons&lt;/h3&gt;As I have said, statically typed languages can perform all these optimizations upfront and create, as example, &lt;a href="http://de.wikipedia.org/wiki/Low_Level_Virtual_Machine"&gt;LLVM&lt;/a&gt; byte code which is highly portable and extremely fast. As example, both C and C++ can be compiled into LLVM.&lt;br /&gt;There is also a disadvantage in this process ... if some unexpected input occurs runtime, the whole logic could crash, be compromised, or exit unexpectedly.&lt;br /&gt;Latter part is what will rarely happen in scripting world, but it can be also a weak point for application stability and reliability since things may keep going but who knows what kind of disaster an unexpected input could cause.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;What If ...&lt;/h3&gt;Try to imagine we have created unit tests for a whole application or, why not, just for a portion of it (module).&lt;br /&gt;Try to imagine these tests cover 100% of code, a really hard achievement on web due feature detections and different browsers behaviors, but absolutely easy task in node.js, Rhino, CouchDB, or any JS code that runs in a well known environment.&lt;br /&gt;The differential Mocking approach to solve the web situation requires time and effort but also what JS community is rarely doing, as example, is to share mocks of same native objects in both JS and DOM world. This should change, imo, because I have no idea how many different mocks of XMLHttpRequest or document we have out there and still there is no standard way to define a mock and listen to mocked methods or properties changes in a cross platform way.&lt;br /&gt;Let's keep trying imagine now ... imagine that our tests cover all possible input accepted in each part of the module.&lt;br /&gt;Try to imagine that our tests cover exactly how the application should behave, accordingly with all possible input we want to accept.&lt;br /&gt;It's insane to use typeof or instance of operator per each argument of each function .... this will kill performances, what is not impossible is to do it in a way that, once in production, &lt;a href="http://webreflection.blogspot.com/2010/08/objectdefineproperty-but-strict.html"&gt;these checks are dropped&lt;/a&gt;.&lt;br /&gt;Since with non tested input we can have unexpected behaviors, I would say that our application &lt;strong&gt;should fail&lt;/strong&gt; or exit the moment something untested occurs .... don't you agree?&lt;br /&gt;How many less buggy web apps we would have out there ? How much more stable and trustable could we be ?&lt;br /&gt;The process I am describing does not exist even in statically typed languages since in that case developers trust unconditionally the compiler, avoiding runtime misbehavior tests ... isn't it ?&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;The Point Is ...&lt;/h3&gt;We wrote our code, we created 100% of code coverage and we created 100% of expected inputs coverage. At this point the only thing we are missing to &lt;strong&gt;compile JavaScript into LLVM&lt;/strong&gt; is a tool that will trace, and trace only, the test while it's executed and will be able to analyze all cases, all types, all meant behaviors, all loops, and all function calls, so that everything could be statically compiled and in separate modules ... how great would this be if possible today?&lt;br /&gt;&lt;br /&gt;Just try to imagine ...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34454975-2889867172226370799?l=webreflection.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel="replies" type="application/atom+xml" href="http://webreflection.blogspot.com/feeds/2889867172226370799/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=34454975&amp;postID=2889867172226370799" title="8 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/2889867172226370799" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/34454975/posts/default/2889867172226370799" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/WebReflection/~3/sW45mWZHGSw/missing-tool-in-scripting-world.html" title="The Missing Tool In Scripting World" /><author><name>Andrea Giammarchi</name><uri>http://www.blogger.com/profile/16277820774810688474</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="http://www.3site.eu/graphic/blogspot_profile.gif" /></author><thr:total>8</thr:total><feedburner:origLink>http://webreflection.blogspot.com/2011/10/missing-tool-in-scripting-world.html</feedburner:origLink></entry></feed>

