javascript - 我误解了 JavaScript 中的 "this"关键字

标签 javascript this

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();

http://jsfiddle.net/M5aeE/

foo() 显示“hello”,因为 this 绑定(bind)到调用 foo() 的当前对象,它是 window

我们可以像这样重写这个行为。

window.string5 = "hello";
var myObj = {string5:"World!"};
function foo() {
   alert(this.string5);
};
var woo = foo.bind(myObj);
woo();

http://jsfiddle.net/M5aeE/1/

如您所见,我使用了 bind(myObj) 来更改 this 引用的内容。

Javascript 中的关键字 thisnew 的行为方式与它们在其他语言中的行为方式不同,因此很难理解。

当您需要确定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/

相关文章:

javascript - 仅向来自 Facebook 的用户显示 DIV

javascript - 在表行 jquery 的创建和销毁之间切换

javascript - 使用 jquery 将 javascript 变量发送到提交时的 Rails 变量

JavaScript this 关键字惊喜

javascript - 'this' 和普通变量声明的区别

javascript - 词法 this 和闭包

javascript - jQuery:检查元素是否存在(可以通过 ajax 添加)

javascript - 缺少 Google map RouteBoxer API

jquery - 如何让jQuery插件函数返回内在值

javascript - 在 JQuery 方法中设置匿名函数的 'this' 上下文