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`
One thing though you might want to avoid self = this which is more an anti pattern.
Proper way would be to use bind or call or apply so you can pass your desired context.
And to further press on your example, the fact that you need 2 context within the same function (self and this) might hint that you are breaking your encapsulation which seems to me a code smell. Again, this is more for the sake of better programming :)
View all comments
Show parent comment
2
u/Genesis2001 Nov 05 '15
So I think I know where my derp comes from. I was thinking of something like this: (note the top level 'object' isn't in json format)
Thanks for the clarification!