In fact in JavaScript each function
has its own scope
, so inside the keyup
callback this
won't refer to foo
but it will refer to the $("#inputbox")
, which doesn't have a property called str
, that's why you got undefined
. This means that you can't access foo.str
inside the keyup
callback scope.
What you can do is to follow the Module
pattern code style and to store the str
of foo
inside a variable
then access it inside the keyup
callback:
function foo() {
var str = "some text";
var _self = this;
_self.str = str;
$('#inputbox').keyup(function (e) {
alert(str); //<-- This will output "some text"
alert(_self.str); //<-- This will output "some text" too
});
}