javascript中的this指向问题

This关键字:

1、this指向调用该函数的对象

通常情况下,定义一个变量、一个函数,都是作为window的属性、方法的

Var info=’hello’;

Function sayhi(){

This.style.color=’red’;

}

全局变量info 其实是window.info=’hello’;

调用sayhi() 其实是window对象在调用,即window.sayhi() 通常情况下省略window,直接调用。所以this.style.color中的this指向的是window。

2、通过new关键字实例化时,改变this指向,不在指向window。而是指向实例化的这个对象。

示例:

Function Student(){

This.name=”lydia”;

}

Var stu=new Student();

此时 this指向stu

3、匿名函数具有全局性,因此在匿名函数中this指向window对象

Var name=’outer’;

Var obj={

name:’inner’,

Say: function (){

Alert(this.name); //inner this指向调用它所在函数的那个对象 即obj

(Function (){

Console.log(this.name); //outer this指向window

}());

}

}

Obj.say();

var name = "window";

var Bob = {
    name: "Bob",
    showName: function(){
        alert(this.name);
    }
};

var Tom = {
    name: "Tom",
    showName: function(){
        var fun = Bob.showName;
        fun();
    }
};

Tom.showName();  //window

4、在事件监听中this指向调用该监听事件的对象

ele.addEventListener(‘click’,handler,false);

或者 ele.onclick=handler;

Function handler(){

this.style.color=’green’; //this指向绑定事件时的元素ele

}

This被解析为将函数作为其方法的对象

挑战题:

1、

var name = "Bob";  
var nameObj ={  
    name : "Tom",  
    showName : function(){  
        alert(this.name);  
    },  
    waitShowName : function(){
        var that = this;
        setTimeout(function(){                
            that.showName();
        }, 1000);
    }
};  
 nameObj.waitShowName();  

2、

var name = "Bob";  
var nameObj ={  
    name : "Tom",  
    showName : function(){  
        alert(this.name);  
    },  
    waitShowName : function(){
        var that = this;
        setTimeout("that.showName();", 1000);
    }
}; 
 
nameObj.waitShowName();  

3、

var fun = new Function("alert(this)");  
fun();

答案:1、Tom 2、报错: “that is not defined” 3、[object Window]

1、中由于在定时器中使用的是一个函数,因此在函数定义时,是可以读取到that变量的。 个人理解:类似于闭包,可以读取外面的变量,所以可以读取that

setTimeout(function(){         //在执行该函数时,此处 this指向window 而that指向的是nameObj对象 
            that.showName();
        }, 1000);
2、由于使用的是一个字符串,需要先用eval执行,解析成函数,再执行,而这一过程发生在定时器指定的时间间隔后,因此,在使用eval解析后的函数中,this实际已经指向window,而that是不存在的变量,所以会提示 “that is not defined”