3 ms·
http://ejohn.org/apps/learn/#13 http://ejohn.org/apps/learn/#13 This is exactly the kind of thing that makes Javascript so disappointing. ninja is an object, t
by gizmo 17y ago
http://ejohn.org/apps/learn/#13 http://ejohn.org/apps/learn/#13
This is exactly the kind of thing that makes Javascript so disappointing. ninja is an object, that has a slot yell. yell refers to a function/closure. Samurai is a _new_ object, with a _new_ slot, that _independently_ refers to the same function that yell in ninja refers to.
And yet, when ninja is deleted/collected the function yell disappears. This is insanity. In javascript
function(n) { blah }
should be a simple expression that creates a heap object, and heap objects should live until it becomes unreachable, at which point it may be collected. So unless _function_ is not an ordinary expression that creates a first class object, this cannot _possibly_ go wrong.
And yet it does.
Can anybody think of a justification for this absurd behavior?
- praptak 17y agoI believe you misunderstood the behaviour of the code. The ninja.yell function is a proper object, it does not disappear and samurai.yell refers to it all the time. What goes wrong is this: when it tries to call itself recurively by using ninja.yell, ninja already refers to null. That's when it fails. The moral of this slide is "If you want a function to call itself, better give it a name and refer to it by the name instead of relying on bindings that are outside the scope of the function." This has a followup in the next slide, where exactly this happens.
- axod 17y ago>> "If you want a function to call itself..." Or just use the arguments.callee property which allows you to call the function from itself without worrying about names. edit: oops, just seen that's on a later slide.
- tlrobinson 17y agoExcept in ES5 strict mode :-/
- gb 17y agoYou can still do it, and without a Y combinator or anything like that too: var ninja = { yell: function () { var yellLocal = function(n) { return n > 0 ? yellLocal(n-1) + "a" : "hiy"; } return yellLocal; }() }
- gizmo 17y agoYou're right. I didn't see it was the recursive function that throws the exception.