javascript 中的 this

共五种情况:

//1、默认 指向:window
console.log(this === window); //true;
//2、函数调用 指向:window
var fn = function(){
console.log(this === window); //true;
};
//3、对象方法调用 指向:对象
var o = {};
o.fn = function(){
console.log(this === o); //true;
};
//4、new的对象内 指向:该实例化对象(新创建的对象)
//5、call, apply 中,指向第一个参数

另外,举两个容易误会的例子:

第一个例子

var o = {};
o.fn = function(){
console.log(this === o); //true
var meth = function(){
console.log(this === window); //true
}
meth();
}
o.fn();
//这里第二个true容易误解,其实是属于第二种情况。

解决办法:

var o = {};
o.fn = function(){
var that = this; // 用that 代替
var meth = function(){
console.log(that=== o); // true
}
meth();
}
o.fn();


第二个例子,是this在运行时,延迟绑定

var o = {};
o.fn = function(){
console.log(this === window); //true
}
var soda = o.fn;
soda();



整理自 javascript 神秘花园




posted @ 2012-03-02 12:48  王冶soda  阅读(215)  评论(0编辑  收藏  举报