In the following code, the line obj.sayhello()
means that sayhello
executes in the context / scope of obj
. str
is not defined (via var
) in the sayhello
method. JS will look up the variable in the scope i.e. in the obj
which clearly has a str
property. Why does the script throw a ReferenceError
?
Uncaught
ReferenceError
:str
is not defined atObject.sayhello
var obj = {
str: "hello",
sayhello: function(){
return str;
}
};
obj.sayhello();