More Crockford videos. I haven't laughed that good in a long time.
One bit that was amusing is the following:
return {
ok : false
};
This works well to return an object literal
return
{
ok: false
};
is a total failure. So go with the first form.
Why does it fail? Well, the language inserts semicolons and does not care about useless statements so it sees:
return ; \\returns undefined
{ \\naked block. useless since no scope, but who cares
ok: false \\label in a totally useless fashion. which is fine. It evaluates false even if it is useless
\\ no semi-colon? no problem, we have insertion
}; \\not a statement so no semi-colon needed. But empty statement okay so it evaluates ;
\\and does nothing.
So all in all, this is a classic case of trying to do the right thing screws you.
JavaScript is a language with lots of power, but it requires good discipline.
One key pattern is encapsulation using closures and functions as data. So
var example = (function () {
var constant = ['stuff', 'more'];
var state = 0;
return function (dig) {
state += 1;
if (constant[dig] !== undefined) {
return [constant[dig], state];
};
}) () );
example(0); //returns ['stuff', 1]
example(0); //returns ['stuff', 2]
example(1); //returns ['more', 3]
//end program
So in this one snippet we see how inner functions access outer functions either to save on initialization times (constants of the function) or to maintain state between calls. It can also be used to have generator functions that generate custom functions. Notice the outer parentheses in example--these are not needed by language, but human maintainers enjoy being told that this function is being evaluated, not assigned. It is the inner function (need not be a function) that is getting assigned as that is what is being returned.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment