帶着如下幾個問題:
一、call 和 apply 的區別在哪?
二、call 在什麼狀況下使用? apply 在什麼狀況下使用?
三、apply 有哪些妙用?數組
apply 和 call 均可以劫持另一個對象的方法,繼承另一個對象的屬性,下面咱們看一些他們的不一樣在哪裏;
下面看代碼是如何體現的:app
Function.apply(obj, arguments)方法能接收兩個參數 obj:這個對象的 this 指向將代替Function類裏this指向 arguments:這個是數組,它將做爲參數傳給Function(args-->arguments)
apply 示例:函數
function Person(name, age) { this.name = name; this.age = age; } function Boy(name, age, job) { Person.apply(this, arguments); this.job = job; } const boy = new Boy('Phoenix', 27, 'programmer'); console.log(boy.name, boy.age, boy.job); // Phoenix 27 programmer
上面代碼中 Boy 構造函數中,咱們並無構造 name 和 age 參數;
可是實例化對象 boy 中仍是有完整的三個參數,這就是 apply 的魅理。學習
call 示例:this
function Person(name, age) { this.name = name; this.age = age; } function Boy(name, age, job) { Person.call(this, name, age); this.job = job; } const boy = new Boy('Phoenix', 27, 'programmer'); console.log(boy.name, boy.age, boy.job); // Phoenix 27 programmer
上面的 Boy 中的name 和 age 參數指向的都是 Person 中的 name 和 age 參數;
由上面兩個示例能夠發現 call 和 apply 的區別僅僅在於參數形式不一樣;
apply方法的第二個參數是由參數組成的數組;
而call方法的第二個參數則是被展開的數據,在ES6中也能夠是 Function.call(this, ...arguments),效果同樣;prototype
那麼 apply 方法都有哪些方便的功能呢;
(1)Math.max() 這個方法會在全部的參數中查找到最大的一個;code
Math.max(1, 2, 3) // 3
若是這個方法若是這能夠這樣使用那真是太雞肋了;
若是他能傳遞一個數組,咱們在數組中查找到最大的數字那不是很好用嗎?對象
const arr = [1, 2, 3]; Math.max.apply(null, arr) // 3 // 固然 ES6 出現之後 有了展開運算符 ... 能夠得到同樣的結果 Math.max(...arr); // 3
固然apply方法不僅是這一個地方用的到
加入咱們想把兩個數組整合到一塊兒;
(2)Array.prototype.push.apply(arr1, arr2);繼承
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; Array.prototype.push.apply(arr1, arr2); console.log(arr1); // [1, 2, 3, 4, 5, 6] // ES6 之後 // arr1.push(...arr2) 效果同樣
其實在 ES6 出現之後,好多以往被 apply 能夠展開運算的功能基本都被 ...展開運算符代替了;io
總結:
你們從上面能夠學習到 apply 和 call 的用法,也嚐到了ES6中的甜,但也不要忘記之前但知識哦,語法糖但實現原理也都是源於老版本的JS,基礎尤其重要!