I know this is kind of a silly example– but why does this code result in an error that bar is not defined. Wouldn’t javascript look to see if bar was a property of “this” object. I know that adding this, fixes the problem– but this tends to throw me off. In other programming languages (C#) for instance, this is usually redundant– why does it need to be added in the code below?
var myObject = {
foo : function(){
alert(bar);
},
bar : "hello world"
};
myObject.foo();
No. It looks at what variables are in scope, not what properties are members of the current context.