Posts

Showing posts with the label function

I Heard You Like To Write Less

Update apparently this proposal is being considered in es-discuss ... not the implicit return so far but the " redundant " function keyword. This is last draft from Brendan Eich: FunctionDeclaration: function Identifier ( FormalParameterList_opt ) { FunctionBody } Identifier ( FormalParameterList_opt ) [no LineTerminator here] { FunctionBody } ShortFunctionExpression: Identifier_opt ( FormalParameterList_opt ) [no LineTerminator here] { FunctionBody } Identifier_opt ( FormalParameterList_opt ) => InitialValue I'm @qconlondon waiting for the next talk so I decided to take a couple of minutes to blog about this little experiment. In ES-Discuss developers are still talking about function keyword, if it's needed or not. I believe the fact CoffeeScript has no explicit function is one of the major reasons devs have been attracted so I made it even simpler. Just Drop The Function With current ES 3, 5, or 5.1 syntax I can't really see problems or ambigui...

JSON.stringify Recursion + Max Execution Stack Exceeded

I believe this is a common problem, and we had a similar one today while debugging. JSON methods do not support recursion ... which is the only thing I am really missing back to PHP serialize days. Recursion Is Bad Well, I would say cyclic references are never that good but sometimes these may happen and, specially while testing and debugging, it's more than useful to understand what happened there. If you have cyclic/cross references in your code I suggest you to use approaches which aim is to avoid these kind of direct links. Harmony Collections , specially Map and WeakMap, are indeed good helpers to reference indirectly objects without creating, hopefully, first level links and/or recursions. How To Serialize Anyway JSON.stringify() accepts a second argument called replacer . I won't explain more than MDN about its potentials, but it can be really handy to avoid recursions. A simple way to do it is indeed to store in a stack already parsed objects, included the object itse...

Improving Function.prototype.bind

There are a couple of things I have never liked that much about Function#bind and this post is about proposing a pattern hopefully better than common one. At The End Of The Function A common argument about parentheses around inline invoked functions is that developers can easily recognize them. // considered ambiguous var someThing = function () { return {}; }(); // considered not ambiguous var someThing = (function () { // note the parenthesis return {}; }()); // note the parenthesis // exact same behavior of latest one // but considered slightly ambiguous var someThing = (function () { // note the parenthesis return {}; })(); // note the parenthesis The parentheses version apparently wins but, specially when no assignment is needed, I believe these are even less ambiguous: -function(){ alert("OK"); }(); +function(){ alert("OK"); }(); !function(){ alert("OK"); }(); Of course if there is an operator that function will be executed, why on earth...

Function.prototype.notifier

There are way too many ways to stub functions or methods, but at the end of the day all we want to know is always the same: has that function been invoked ? has that function received the expected context ? which argument has been passed to that function ? what was the output of the function ? Update thanks to @bga_ hint about the output property in after notification, it made perfect sense The Concept For fun and no profit I have created a prototype which aim is to bring a DOM like interface to any sort of function or method in order to monitor its lifecycle: the "before" event, able to preventDefault() and avoid the original function call at all the "after" 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 the "error" event, in case we want to be notified if something went wrong during function execution the "handlerer...

Taking The Bat-Formula To The Next Level

When you wake up on Sunday morning with upside-down stomach and batcode in mind, you may realize it's time to rest a bit. with (/*Bat*/Math) Array(16).join( pow(/*JOK*/E/*R*/, cos, E/*vil*/) ) + "batman"; The output is the same produced by the original bat-formula : 'NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNbatman' Have a nice Sunday.

bind, apply, and call trap

quick one out of ECMAScript ml var // used to trap function calls via bind invoke = Function.call, // normal use cases bind = invoke.bind(invoke.bind), apply = bind(invoke, invoke.apply), call = bind(invoke, invoke) ; What Is It This is a way to trap native functions method in a handy way. Used in a private scope, it can address these methods once so that we can rely nobody can possibly change them out there for some script injection and only if we are sure the script has been loaded at the very beginning. How To Use Them Here few examples: // secure hasOwnProperty var hasOwnProperty = bind(invoke, {}.hasOwnProperty); // later on hasOwnProperty({key:1}, "key"); // true hasOwnProperty({}, "key"); // false // direct slice var slice = bind(invoke, [].slice); slice([1,2,3], 1); // 2,3 slice(arguments); // array // direct call call([].slice, [1,2,3], 1); // 2,3 // direct apply apply([].slice, [1,2,3], [1]); // 2,3 // bound method var o = {name:...

Anonymous Style

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself. I have already commented the popular JavaScript Code Convention article, but latest cited sentence is probably the only one I have never been sure about. Why Bother Actually, I have always found the expression: var something = function(){ // do stuff // return something }(); // invoke kinda enough to invoke inline a function expression. Somebody argued that above style is ambiguous. Since an inline invoke could be performed against a massive function body, the point is that we may need to scroll 'till the end of the function expression to know if it has been executed or not. In my opinion, whenever there is a function expression, we should always check the end of this function or we'll never be sure about the assigned value. Fair enough, even if the fun...

Function.prototype.bind

Quick post about a fast Function.prototype.bind implementation. Function.prototype.bind function bind(context:Object[, arg1, ..., argN]):Function { return a callback able to execute this function passing context as reference via this } In few words, if we have a generic object, we don't necessary need to attach a function to create a method: // a generic function function name(name) { if (name == null) return this.name; this.name = name; return this; } // a generic object var wr = {name:"WebReflection"}; // a callback with a "trapped" object var fn = name.bind(wr); alert([ // wr has not been affected wr.name, // WebReflection // fn can always be called fn(), // WebReflection fn("test") === wr, // true fn(), // test wr.name // test ].join("\n")); Designed to ensure the same context whatever way we decide to use the callback, included call, apply, setTimeout, DOM events, etc, Function.proto...

Good Old And Common JavaScript Errors

... I won't write any introduction, but I'll let you comment, OK? for loops (plus ++i) for(i = 0; i // global i defined for(var i = 0; i // cache the length if it won't change during the loop // associate once only under certain conditions to speed up for(var i = 0; i // there is absolutely nothing wrong in above loop Few people told me something like: " doode, if you use ++i at the end you need to write i " ... basically the for loop has been rarely understood, let me try again: // directly from C language, 1972 for( // optional inline declaration, coma accepted for more vars ; // optional condition to verify // if undefined, it loops until a break is encountered // this condition is performed BEFORE the first loop // if false, the loop will never be executed ; // optional POST operation, it will never be executed // if the condition is false, "", 0, or null // it is executed in any case AFTER the loop, if any ){}...

Named function expressions demystified III

Update For those interested about Internet Explorer scope resolution, I summarized everything in 5 slides . This is hopefully the end of the Named function expressions demystified trilogy, where here you can find episode I , and episode II . Juriy knows I am hard to convince, but apparently he is not better than me at all ... Inglorious Correction Sure, it's better than nothing, but after I have spent dunno how many tweets plus 2 posts, all I have obtained is a small correction in the whole article (and you have to scroll a bit before): Generally, we can emulate function statements behavior from the previous example with this standards-compliant (and unfortunately, more verbose) code: var foo; if (true) { foo = function foo(){ return 1; }; } else { foo = function foo() { return 2; }; }; // call the function, easy? foo(); Above snippet is the best solution in the entire article but probably to avoid my name in article credits, and it does not matter since I ...

Named function expressions demystified II

Update If after this reading things are still the same, please read the part 3 of this post, thanks. I have been criticized just for fun and in a impulsive way without analysis or tests (I am not talking about Juriy who gently replied with interesting points in the part 1 of this post - and I replied back). First of all, if the purpose of an article is to describe a behavior and provide a solution, there should not be any challenge or run for the copyright ... we are developers, and we want the best solution, for us and others, if this solution has been published. Specially for a complicated language as JavaScript is, Virtual Machine and cross browser troubles speaking, is really difficult, sometimes impossible, to find the ultimate and perfect solution, so let's keep the argument in a professional way, agree? What Is Wrong With Juriy Solution Somebody does not get it, and it could be my fault. So this is about inconsistencies, and I'll show you Juriy code to avoid any kin...

Named function expressions demystified

Update If after this reading things are still the same, please read the part 2 of this post , thanks. This is a re-post, and few considerations, about the good Juriy article , which I suggest for every JavaScript developer with a deeper knowledge than just an API (jQuery or others). Github For Everything! My first consideration is about github, something I've never used that much since via Google Code I feel pretty comfortable with subversion. I find truly interesting the way Juriy is tracking his documentation, I've never thought about an article, as my old JavaScript Prototypal Inheritance could be, in a code repository as kangax did: good stuff! My Alternative Solution There are few extra consideration to do over Juriy explanation, plus minor inconsistencies. The first thing is that Internet Explorer basically manages Function expressions and Function declarations in the same way, there's no such VS in the middle. The fact we assign the function to a whatever named v...

How to inject protected methods in JavaScript - Part II

As a performances maniac, I've found another way to inject protected methods, or something similar, without unnecessary overload of each public method. Of course, precedent way is definitively more clear, linear, but if you have a constructor.prototype with a lot of private methods, the overload process will be a wall in front of method execution speed. Each time you will use a public method, you have to set, and unset, every protected method, and at the same time, as explained in my precedent post, you cannot send the object outside during public method execution, because it will expose every method, protected included. This new proposal is based on a Function like strategy, applied to instances: apply, and call. Please have a look at this prototype function: function prototype(constructor, public, protected){ // webreflection - mit style if(protected){ public.apply = function(callback, arguments){ return (callback.charAt(0) === "_" ? protected : this)[callback]....