将`this`传递给.keyup()[复制]

问题描述 投票:-1回答:2

问题:

我正在尝试使用this.str。有没有办法将this传递给.keyup()函数?

function foo() {
    var str = "some text";
    $('#inputbox').keyup(function (e) {
       alert(str); //<-- This will output "some text"
       alert(this.str); //<-- This will output "undefined"
    });
}
javascript jquery function scope this
2个回答
1
投票

您可以将this存储在变量中,通常将变量命名为_this_self_me

像这样:

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>

你也可以像这样使用箭头函数:

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>

你也可以使用一些Function.prototype方法,如applycall来设置this。但是在这种情况下,这样做没有多大意义,因为你可以看到:

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>

1
投票

事实上在JavaScript中每个function都有自己的scope,所以在keyup回调this内部不会引用foo,但它将引用$("#inputbox"),它没有一个名为str的属性,这就是为什么你得到undefined。这意味着您无法访问foo.str回调范围内的keyup

你可以做的是遵循Module模式代码风格,并将strfoo存储在variable中,然后在keyup回调中访问它:

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
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.