2011-03-11 85 views
0

很简单的问题...JavaScript变量说明

想知道什么

“这个”变量表示在JavaScript ... 感谢

+0

从创建者Brendan Eich自己那里获取; http://www.amiutewithbrendan.com/pages/20110303 – 2011-03-11 09:59:19

回答

0

JavaScript中的this变量与任何其他语言一样,指的是当前对象。 例如:

document.getElementById('link1').onclick = function() 
{ 
this.href = 'http://google.com'; 
} 

在onclick处理程序,这将是指你的ID得到了一个DOMElement。

0

在JavaScript中这始终是指功能的“所有者”我们正在执行,或者说,正在执行一个函数是一个方法的对象。
查看下面的链接了解更多解释。
http://www.quirksmode.org/js/this.html

2

宽泛地说,它代表了什么是点的左侧,当你调用该函数:

// inside of f, this = x 
x.f(1, 2, 3) 

// inside of f, this = c 
a.b.c.f(1, 2, 3) 

有一些例外的规则的。

首先,如果你没有点:

​​

其次,你可以使用的方法call和/或apply明确设置的this值:

// Invokes f with this = myVar, not x (arguments 2 an onward are the ordinary arguments) 
x.f.call(myVar, 1, 2, 3) 

// Invokes f with this = myVar, not x (arguments are passed as an array) 
x.f.apply(myVar, [1, 2, 3]) 

第三,当你使用new,this调用函数将引用新创建的对象:

// inside of f, this = a new object, not x 
new x.f(1, 2, 3)