变幻莫测的this的指向

1、事件调用环境

谁触发事件,函数里面的this指向的就是谁

let box = document.querySelect('.box');
box.onclick= move();
function move(){
    
    
	this.style.left='100px';
}

2、全局环境

浏览器下指向window ,node环境下指向 module.exports

3、函数内部

1 ) this最终指向的是调用它的对象

var obj = {
    
    
	a:10,
	b:funciton(){
    
    
		console.log(this);
}
obj.b();
	

2 ) 函数被多层对象所包含,如果函数被最外层对象调用,this指向的也只是它上一级的对象

var obj = {
    
    
	a:10,
	b:{
    
    
		fn:function(){
    
    
			console.log(this);
		}
	}
}
var abc = obj.b.fn;
abc();//window      this 最终指向的是调用它的对象,而不是声明时的对象

3 ) 构造函数中的this指向的是实例对象

function fn(){
    
    
	this.num = 10;
}
fn.num = 20;
fn.prototype.num=30;
fn.prototype.method=function(){
    
    
	console.log(this.num);
}
var prototype= fn.protype;
var method = prototype.method;
new fn().method();//10
prototype.method();//30
method();//undefined

4 ) 如果构造函数中有return 如果return的值是对象,this指向返回的对象,如果不是对象,则this指向保持原来的规则,在这里null比较特殊

function fn(){
    
    
	this.numm= 10;
	return 1;//10
}
function fn(){
    
    
	this.numm= 10;
	return [];//undefiend
}
function fn(){
    
    
	this.numm= 10;
	return {
    
    };//undefiend
}
function fn(){
    
    
	this.numm= 10;
	return null;//10
}
var obj = new fn();
console.log(obj.num);

4、箭头函数

箭头函数本身是没有this和arguments的,在箭头函数中引用this实际上调用的是定义时的上一层作用域的this,这里强调一下是上一层作用域,因对象是不能形成独立的作用域的。

let box = document.querySelect('.box');
box.onclick = move;
function move(){
    
    
	var _this = this;
	setTimeout(function(){
    
    
		_this.style.left ='100px';
	},100);
}
function move(){
    
    
	setTimeout(()=>{
    
    
		this.style.left='200px';
	},1000)

5、改变this指向

call 、apply 、bind 都可以修改this指向,区别是传参方式不一样

var box = document.querySelector('.box');
var obj ={
    
    
	fn:function(arg1,arg2){
    
    
		console.log(this);
	}
}
obj.fn.call(box,arg1,arg2);
obj.fn.apply(box,[arg1,arg2]);
obj.fn.bind(box,arg1,arg2)();

注意:如果将修改的this指定为null和undefined时,此时this指向全局对象Window。

猜你喜欢

转载自blog.csdn.net/literarygirl/article/details/111501454