JS中this的指向看这些就够了
2019-09-17 本文已影响0人
追逐_chase

在写JS时会经常使用到this
,就会遇到this的指向问题,主要体现在如下几个方面
-
1.普通函数调用 this指向window
我们知道在JS脚本中,所有的函数或者
声明的变量
其实就是window对象的属性
function fn(){
console.log(this);
}
fn();
//打印是 :window
-
2. 使用new构造函数调用, this指向新创建的对象
function Person(name,age){
this.name = name;
this.age = age;
this.show = function(){
console.log(this );
}
}
var p1 = new Person("CC",18);
p1.show();
-
3.函数作为对象方法调用 this指向当前对象
//创建的对象
var object= {
name:"cc",
show:function(){
console.log(this);
}
};
//此时调用 this指向 object
object.show();
-
4. 函数上线文(apply | call ) this指向第一个参数
-
apply 和 call
都是借调函数,改变this
的指向
-
var object= {
name:"cc",
show:function(){
console.log(this);
}
};
object.show();
var obj = {
name:"rr"
};
// obj借用object对象的show方法,此时 this指向 obj这个对象
//借用call调用时 this指向的对象是 obj
object.show.call(obj);
注意
:如果 apply和call借用函数,参数不传或者传null,那么this就是原来默认的window