apply和call

前言

  • apply 和 call 可以改变函数执行时的 this 对象。

举个例子

<script>
class ClassA {
	constructor() {
		this.name = 'AA';
	}
 	show() {
		console.log(this.name);
	} 
}

class ClassB {
	constructor() {
		this.name = 'BB';
	}
}

var a = new ClassA();
var b = new ClassB();

a.show(); // output>> AA
a.show.call(b); // output>> BB
ClassA.prototype.show.call(a); // output>> AA
ClassA.prototype.show.call(b); // output>> BB

a.show.apply(b); // output>> BB
ClassA.prototype.show.apply(a); // output>> AA
ClassA.prototype.show.apply(b); // output>> BB
</script>
  • a.show() 这里执行时,this 是你认为的 this
  • a.show.call(b)a.show.apply(b)执行时, this 变成了 b
  • ClassA.prototype.show.call(a)ClassA.prototype.show.call(b)ClassA.prototype.show.apply(a)ClassA.prototype.show.apply(b),传啥啥是this
  • 总结一下:通过 apply 和 call 改变了 show 执行时的 this 。

函数定义

/*apply()方法*/
function.apply(thisObj[, argArray])
/*call()方法*/
function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);

从定义可以看出,apply 接受参数数组,而 call 需要一个一个的写上参数。
嗯,两个函数意思是一样的,只是应用场景不同。

  • 当有了参数数组,那就用apply。
  • 当参数是零散的情况时,那就用call。

参考

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://www.cnblogs.com/lengyuehuahun/p/5643625.html
https://www.cnblogs.com/lengyuehuahun/p/5643625.html
https://blog.csdn.net/youlinhuanyan/article/details/108107380

你可能感兴趣的:(JavaScript)