js中this的指向
一、全局范围内this的指向
<script> console.log(this);//全局范围this指向window对象 </script>

二、调用函数时,函数里面的this指向
<script> function foo(){ console.log(this);//函数调用this指向window对象 } foo(); </script>

三、调用对象里面的方法时,this指向的是当前的对象
<script>
var a = {
name:'name',
foo:function(){
console.log(this);//方法调用this指向调用这个方法的对象
}
};
a.foo();
</script>

四、调用构造函数里面的方法时,this指向的是实例化的对象
<script>
var obj = function(name){
this.name = name;
}
obj.prototype.foo = function(){
console.log(this);
}
per = new obj("张三"); //通过构造函数调用this执行的的实例化的对象
per.foo();
</script>

五、call、apply都可以改变this的指向,他们的区别是:传参数的时候call是传字符串,apply传的是数组,this的指向都是指的第一个参数
<script> function foo(name,type){ this.name = name; console.log("这是使用了"+type+"的指向:",this); console.log(this.name); } foo(); var bar= { age:"22" }; foo.call(bar,"张三","call"); //call可以改变this的指向,没有使用call是this指向全局对象window,使用了call,this指向他所对应的第一个参数 foo.apply(bar,['李四','call']); //call可以改变this的指向,没有使用call是this指向全局对象window,使用了call,this指向他所对应的第一个参数 </script>


浙公网安备 33010602011771号