这个问题在这里已有答案:
问题:
我正在尝试使用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"
});
}
您可以将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
方法,如apply
或call
来设置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>
事实上在JavaScript中每个function
都有自己的scope
,所以在keyup
回调this
内部不会引用foo
,但它将引用$("#inputbox")
,它没有一个名为str
的属性,这就是为什么你得到undefined
。这意味着您无法访问foo.str
回调范围内的keyup
。
你可以做的是遵循Module
模式代码风格,并将str
的foo
存储在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
});
}