JavaScript apply() call()学习

个人理解,apply()、call()的作用就是"借用"其他的函数,完成事情,第一个参数都是运行时的对象

apply()与call()区别

apply()第二个参数传入的是数组,call()第二个传入的参数是一串变量(记忆方法:call打电话,需要一个一个拨)

以下代码是网上普遍的例子

1.

function person (name, age) {
	this.name = name;
	this.age = age;
}
function student (name, age, grade) {
	person.apply(this, [name, age]);
	// person.apply(this, arguments);
	this.grade = grade
}
var player = new student('kobe', 19, 1);
console.log(player)

apply的第一个参数this,指的是player实例,第二个参数为数组,变量名需要与person函数的形参一一对应,也可以直接传入arguments对象(取前面两项),控制台打印结果如下

2.

计算数组[-1, 2, 3, 4, 5]的最大值

var arr = [-1, 2, 3, 4, 5]
console.log(Math.max.apply(null, arr)) // 5

简单粗暴,网上有些写法是Math.max.apply(this, arr),这里的this我觉得不对,因为不需要指定对象

3.

自己写的比较函数

function getMax (a, b) {
	console.log(a > b ? a : b);
}
function foo (x, y) {
	getMax.apply(null, [x, y])
}
foo(1, 2) // 2

猜你喜欢

转载自blog.csdn.net/chenjineng/article/details/81316475