<script>
//这里this代表window
var obj=function(){
alert(this);//window
}
obj();
//这里this代表window
function obj(){
alert(this);//window
}
obj();
//这里this代表obj这个对象
var obj={
a:function(){
alert(this==window);
}
}
obj.a();
//-----改变this指向--------
//方式一,通过apply来改变
obj.a.apply(window);//打印true
//方式二,通过call来改变
obj.a.call(window);//打印true
//方式三,通过new来改变
function Person(name,age){
this.name=name;
this.age=age; this.sayName=function(){alert(this.name);};
}
var p1 = new Person("mokai",27);
var p2 = new Person("gongkai",24);
p1.sayName();//打印mokai
p2.sayName();//打印gongkai
</script>
百度百科:
上下文对象
上下文对象指的就是this对象。它是一个只能读取而不能直接赋值的对象(就是你只能对this拥有的属性和方法赋值)。上下文对象在javascript可以说发挥的淋漓尽致。
如果你在一个对象(Object)中使用this,指的就是这个对象
var obj={
getThis:function(){
return this;
}
};
alert(obj.getThis===obj); // true
同样的,在作用域中已经提到过文档中javascript对象都属于window,那么下面这个例子
alert(window===this);
也将提示true。
上下文对象在事件侦听器中指的就是发生事件的对象
document.body.addEventListener('click',function(){
alert(this===document.body); // true
},false);
this在构造函数中则是指实例
function Person(name){
thisname=name;
}
var Sam=new Persom();
这里this指的就是Sam。