JavaScript中的this关键字与Java等面向对象语言中的this关键字的含义并不相同,在Java中this关键字指当前对象,而在JavaScript,this关键字则要灵活的多
一,全局变量和全局函数属于全局对象,故通过this关键字调用全局变量或在全局函数中使用this关键字时,this关键字指向全局对象
通过this关键字调用全局变量
var name = 'sean';
this.alert(this.name);//sean
window.alert(window.name);//sean
在全局函数中使用this关键字
var name = 'sean';
function getName(){
//this.name相当于window.name
console.log(this.name);//sean
}
getName();
二,构造函数中的this关键字指向新创建的对象
function Rectangle(width, height){
this.width = width;
this.height = height;
console.log(this);//[object Object]{height: 5, width: 10}
}
var rectangle = new Rectangle(10, 5);
如果直接调用Rectangle函数,而不是将其作为构造函数使用,参考第一条,this关键字指向全局对象
function Rectangle(width, height){
this.width = width;
this.height = height;
console.log(this);//[object Window]
}
Rectangle(10, 5);
三,对象方法中的this关键字指向调用这个方法的对象
var obj = {
name : 'sean',
getName : function(){
//this.name就相当于obj.name
console.log(this.name);//sean
}
}
obj.getName();
看看下面这个例子:
var name = 'global';
var obj = {
name : 'sean',
getName : function(){
console.log(this.name);
}
}
var a = obj.getName;
a();
上面的代码相当于:
var name = 'global';
var obj = {
name : 'sean',
getName : function(){
console.log(this.name)
}
}
var a = function(){
console.log(this.name);//global
};
a();
参考第一条,此时this关键字指向全局对象,可见this关键字的值是在调用时,根据调用对象确定的,而不是在定义时确定的
再来一个示例:
var name = 'global';
var obj = {
name : 'sean',
getName : function(){
function f(){
console.log(this.name);//global
}
f();
}
}
obj.getName();
是不是很奇怪,上面的代码怎么会输出global呢?f()其实相当于window.f(),内部函数定义在全局对象下,上面的代码相当于:
var name = 'global';
function f(){
console.log(this.name);//global
}
var obj = {
name : 'sean',
getName : function(){
f();
}
}
obj.getName();
这里需要再次重申下,this关键字的值是在调用时确定的,而不是在函数定义时确定的,千万别和变量作用域搞混了
四,事件处理程序中的this关键字需要分两种情况讨论
1,如果使用硬编码,this关键字指向发生事件的对象
<html>
<input type='button' οnclick='alert(this);'>//[object HTMLInputElement]
<html>
稍微修改一下这个例子
<html>
<input type='button' οnclick='alert(this.onclick);'>
<html>
显示结果如下
function onclick(event) {
alert(this.onclick);
}
由此可以确定,上面的代码等价于
<html>
<input id='test' type='button'>
<script>
function onclick(event) {
alert(this);
}
document.getElementById('test').onclick = onclick;
</script>
<html>
硬编码部分会被封装为函数,并将该函数赋予input元素的onclick属性,相当于为input元素定义了一个新的方法
当点击button按钮时,onclick函数是作为input元素的方法被调用的,参考第三条,this指向调用该方法的input元素
2,如果使用函数调用方式,this关键字指向全局对象
<html>
<script>
function show(){
alert(this);//[object Window]
}
</script>
<input type='button' οnclick='show();'>
<html>