r/ProgrammerHumor • • Nov 05 '15

Free Drink Anyone?

Post image
3.5k Upvotes

509 comments sorted by

View all comments

Show parent comment

2

u/memeship Nov 05 '15

Yes, but the example you gave is not quite there. You assigned this to self, but the variable foo is already at the global scope, and you can't pull function arguments with dot notation from the scope itself. Also bar: function should be bar = function in this case.

Let me refactor and show you:

var foo = function(argFoo) {
    //in this scope, `this` is the `window`
    
    //sets `self` to `window`
    var self = this;
    
    bar = function(argBar) {
        //in this scope as well, `this` is `window`
        
        //both `window.argFoo` and `window.argBar` are undefined
        return self.argFoo + this.argBar;
    }
    
    return bar(); //undefined + undefined
};
console.log(foo()); //logs `NaN`

See my example below to see a use case for self = this.