1.this是什么?
-
this是函数内的一个隐含参数,每个函数内部都有一个参数this。
-
函数本质上都是通过某个对象来调用的,谁调用该函数,该函数中的this就指向谁。
2.如何确定this的值
-
概括来讲:谁调用指向谁。
-
调用函数的方式有下面几种:
test(); ——>this指向window。 这里是把window省去了,可以写为window.test(); p.test(); ——>this指向p对象。 p调用指向p new test(); ——>this指向当前新建的对象。 test.call(obj); ——>this指向obj。 call()、apply()方法是指定某个对象来调用该方法。
3.练习:确定this指向
<script type="text/javascript">
function Person(color){
console.log(this); //this
this.color=color;
this.getColor=function(){
console.log(this); //this
return this.color;
};
this.setColor=function(color){
console.log(this); //this
this.color=color;
};
}
Person("red");
//window直接调用,this指向window;
var p=new Person("yellow");
// this指向p
p.getColor();
// this指向p
var obj={};
p.setColor().call(obj,"black");
// this指向obj;
var test=p.setColor();
test();
//test()得到了一个方法,
//window调用的test(),所以this指向window;
function fun(){
function fun2(){
console.log(this);
}
}
fun2();
//this指向window;
</script>