-1

Problem:

I am trying to use this.str. Is there a way to pass in this to the .keyup() function?

function foo() {
    var str = "some text";
    $('#inputbox').keyup(function (e) {
       alert(str); //<-- This will output "some text"
       alert(this.str); //<-- This will output "undefined"
    });
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Clinton Lam
  • 687
  • 1
  • 8
  • 27

2 Answers2

1

You can store the this in a variable, It's common to name that variable _this or _self or _me.

Like so:

var str = "some text";
var _this = this;
$('#button').click(function() {
  console.log(str);
  console.log(_this.str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Click Me</button>

You can also use arrow functions like so:

var str = "some text";
$('#button').click(() => {
  console.log(str);
  console.log(this.str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Click Me</button>

You could also use some of the Function.prototype methods like apply or call to set this. But there isn't much sense in doing that in this case as you can see:

var str = "some text";
var _this = this;

$('#button').click(function() {
  onKeyUp.call(_this);
});

function onKeyUp() {
  console.log(str);
  console.log(this.str);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Click Me</button>
nick zoum
  • 7,216
  • 7
  • 36
  • 80
1

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
    });
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78