我误解了这个"这个" JavaScript中的keyworld

时间:2014-03-15 17:20:35

标签: 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函数的独占,JavaScript函数也充当对象,但alert(this.string5)仍然与函数外的string5变量相关联

2 个答案:

答案 0 :(得分:2)

JavaScript函数中的this关键字是指在调用函数时绑定到函数的object

如果将该函数用作回调,有时很难预测该对象是什么。在您的示例中,this引用可能是来自Web浏览器的window全局对象。

例如;

window.string5 = "hello";
function foo() {
   alert(this.string5);
}
foo();

http://jsfiddle.net/M5aeE/

foo()显示"你好"因为this绑定到调用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的行为方式与其他语言的关联方式不同,因此理解起来可能很棘手。

当您需要确定bind引用时,使用this是一种很好的做法。

作为一个例子;

 $("button").on('click',function() {
       // do stuff with this
 }.bind(this));

默认情况下,jQuery会将触发事件的DOM元素绑定到this。您可以通过设置自己的this引用来覆盖它。

答案 1 :(得分:1)

因为您没有将this绑定到任何内容,所以它将绑定到全局主机对象。托管全局变量的那个。