在javascript中所用到的this有以下几个方面:
1 全局下的this 在非严格模式情况下 下面的this都是window
2、对象中的this
如果调用对象中的方法,那么方法中的this指向这个调用者
方法中的this就是当前的对象
如果直接给属性赋一个,this.a 其中a已经定义,此时this指向window,打印得到undefined
3、回调函数中的this指向
事件时特殊的回调函数 事件回调函数中this都是被侦听的对象
所有的函数一旦被写再一个方法中,这个函数就是匿名的回调函数,在该函数中this指向window
function ab(fn){
fn()
}
function cd() {
console.log(this);
}
ab(cd); //window
var obj= {
a:function(fn){
fn();
},
b:function(){
//指向window
console.log(this);
}
}
obj.a(obj.b);
4、ES6的
如果是静态属性或者方法,
一旦被设置为静态属性,this指向都会被设置为当前的类名Box
对于面向对象语言来说,一般在静态属性和方法中不允许使用this
class Box{
//这里的内容是constructor执行后再进行赋值的
// static b=2;
//这里的this指向的是Box类名
// static a = this.b;
b=22;
//这里的this指向b
a=this.b;
constructor(){
// 这里的this指向实例化的对象
console.log(this)
// this.b=3;
}
play(){
console.log(this.a,this);
// 这里的this指向实例化的对象
//
}
static run(){
console.log(Box);
// 这里的this指向为当前类名Box
// 对于面向对象语言来说,一般在静态属性和方法中不允许使用this
}
}
var b = new Box();
b.play();
Box.run();
继承后,静态的方法也会被继承
class Ball extends Box{
constructor(){
super();
}
}
Ball.run();得到一个Ball类名
5 es5
es5的
function Box(){
console.log(this);
//这里的this 构造函数的this new 出的对象
this.c();
}
Box.a=function(){
//这里的this指向 Box
console.log(this)
}
Box.b=3;
Box.prototype.c=function(){
// 这里的this指向当前调用该方法的实例对象
console.log(this)
}
Box.prototype.d = 30;
var h = new Box();
console.log(h);
console.dir(Box)
Box.a();
// b对象中是没有c这个对象属性的,因此就去原型链中找到最近的play方法
//console.log(dir);
h.c();
6 箭头函数
所有箭头函数的this都是指向当前函数外的this指向
var obj={
// a:()=>{
// console.log(this);//this--->window
// },
// b:function(){
// console.log(this);//this--->obj
// },
// c(){
// console.log(this);//this--->obj
// }
// }
var obj={
// a:function(){
// setTimeout(()=>{
// // 因为本来是回调函数,this统一都会被执行window
// // 但是使用了箭头函数,就会全部把这里this指向setTimeout外的this指向,也就是obj
// console.log(this);
// },100)
// }
// }
// obj.a();‘
7、7 call apply bind
当使用call,apply,bind都会将函数中this的指向重新指向到对应的对象