如何修改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 篇原创文章 · 获赞 75 · 访问量 3789

猜你喜欢

转载自blog.csdn.net/anr_safely/article/details/105669067
今日推荐