如何修改javascript中的this指向

修改this指向的目的:

  • 修正(解决隐式丢失时this指向的问题)
  • 继承(利用this的指向,借用其他对象的方法)

1. call()方法

  • 使用方式:函数.call(参数1,参数2…)
  • 参数1:this的新指向
  • 后面所有参数:表示向函数中正常传递的实参,可省略,也可以传多个
  • 返回值:原函数的返回值
function fn(a,b){
   console.log(this);		
   console.log(a);						//world
   console.log(b);						//123
   return "back";
}
fn("world",123);       					//this指向window
var res = fn.call("hello","world",123);	//this指向hello
console.log(res);         				//back

2. apply()方法

  • 使用方式:函数.apply(参数1,参数2)
  • 参数1:this的新指向
  • 参数2:数组,该数组的所有数据被自动展开,传入原函数,可省略
  • 返回值:原函数的返回值
function fn(a,b){
     console.log(this);		
     console.log(a);						//world
     console.log(b);						//123
	 return "back";
}
fn("world",123);       						//this指向window
var res = fn.apply("hello",["world",123]);	//this指向hello
console.log(res);          					//back

3. bind()方法

  • 使用方式:函数.bind(参数1,参数2…)
  • 参数1: this的新指向
  • 后面所有参数:表示向函数中正常传递的实参,可省略,也可以传多个
  • 返回值:修改this指向之后的新函数
function fn(a,b){
	console.log(this);		
	console.log(a);						//world
	console.log(b);						//123
	return "back";
}
fn("world",123);       					//this指向window
var res = fn.bind("hello","world",123);
console.log(res);						//修改this指向之后的新函数 
res();      							//执行返回的新函数,this指向hello
console.log(res == fn);					//false
3种方法的区别:
标题参数1参数2(可省略)返回值
call()this的新指向向函数中正常传递的实参(可多个)原函数的返回值
apply()this的新指向数组(自动解析)原函数的返回值
bind()this的新指向向函数中正常传递的实参(可多个)修改this指向之后的新函数(需手动执行获取this)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值