JavaScript-call()和reply()

call和reply

1.作用

改变 this 指向 – 借用别人的方法实现自己的功能。

2.区别

传参列表不同
call()可以一个一个的传参使用,即把实参按照形参的个数传进去;
apply()只能用一个数组进行传参,即传一个arguments。
all()、apply()这两个函数的第一个参数都是 this 的指向对象。
例如:

Color.apply(this, [outcol, incol]);
Shape.call(this, length, width);

举个实际的例子

		function Color(outcol, incol) {
			this.outcol = outcol;
			this.incol = incol;
		}
		function Shape(length, width, height) {
			this.length = length;
			this.width = width;
			this.height = height;
		}
		function Box(outcol, incol, length, width, height) {
			// 借助已有的实现自己的
			Color.apply(this, [outcol, incol]);
			Shape.call(this, length, width, height);
		}
		var box = new Box("red", "blue", 200, 150, 140);
发布了13 篇原创文章 · 获赞 9 · 访问量 133

猜你喜欢

转载自blog.csdn.net/flower_48237/article/details/103899391