Hacker News new | past | comments | ask | show | jobs | submit login

Yeah, I agree with the other comments -- the greatest JS scoping gotcha involves unbound methods.

    var o = { a:13, add:function(b){ return this.a + b; } };
    o.add(42); // => `55`
    var add = o.add;
    add(42); // => `NaN`, because `this.a` is (presumably) `undefined`
    var a = 3;
    add(42); // => `45`, because `this.a` is resolved to `window.a`, as `window` is the global variable used as the method context when we call an unbound function (which is stupid (`null` would have been a way better choice, Brandon)).
This is the sort of thing you learn and just get over to reach the level of javascript mastery. Yeah, some things are silly. But you know what? You only get to write one language to access the dynamic web.



For unknown reasons, ARC has truncated my code-comment. It read:

// => `45`, because `this.a` is resolved to `window.a`, as `window` is the global variable used as the method context when we call an unbound function (which is stupid (`null` would have been a way better choice, Brandon)).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: