var string5 = "string five outside";
alert( string5 );
function magical( )
{
this.string5 = "string five INSIDE";
alert( string5 );
alert( this.string5 );
}
magical( );
我以为警报(string5);将显示“字符串五外”和警报(this.string5);会显示“string five INSIDE”,因为当我们放这个的时候。在函数内的 JavaScript 变量前面的符号,该变量成为 JavaScript 函数独有的,它也作为一个对象,但 alert(this.string5) 仍然与函数外的 string5 变量相关联
最佳答案
JavaScript 函数中的 this
关键字指的是在函数被调用时绑定(bind)到该函数的 对象
。
如果将函数用作回调,有时很难预测该对象是什么。在您的示例中,this
引用可能是网络浏览器中的 window
全局对象。
例如;
window.string5 = "hello";
function foo() {
alert(this.string5);
}
foo();
foo()
显示“hello”,因为 this
绑定(bind)到调用 foo()
的当前对象,它是 window
。
我们可以像这样重写这个行为。
window.string5 = "hello";
var myObj = {string5:"World!"};
function foo() {
alert(this.string5);
};
var woo = foo.bind(myObj);
woo();
如您所见,我使用了 bind(myObj)
来更改 this
引用的内容。
Javascript 中的关键字 this
和 new
的行为方式与它们在其他语言中的行为方式不同,因此很难理解。
当您需要确定this
引用的内容时,最好使用bind
。
举个例子;
$("button").on('click',function() {
// do stuff with this
}.bind(this));
默认情况下,jQuery会将触发事件的DOM元素绑定(bind)到this
。您可以通过设置自己的 this
引用来覆盖它。
关于javascript - 我误解了 JavaScript 中的 "this"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22427147/