call和apply可以調用函數,改變this,實現繼承和借用別的對象的方法.
調用方法,用一個對象替換掉另一個對象(this)
對象.call(新this對象,實參1,實參2,實參3.....)
對象.apply(新this對象,[實參1,實參2,實參3.....])
call和apply用法
1.間接調用函數,改變作用域的this值
2.劫持其他對象的方法
var foo = { name:"張三", logName:function(){ console.log(this.name); } } var bar={ name:"李四" }; foo.logName.call(bar);//李四 實質是call改變了foo的this指向為bar,並調用該函數
3.兩個函數實現繼承
function Animal(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat"); cat.showName(); //Black Cat
4.為類數組(arguments和nodeList)添加數組方法push,pop
(function(){ Array.prototype.push.call(arguments,'王五'); console.log(arguments);//['張三','李四','王五'] })('張三','李四')
5.合並數組
let arr1=[1,2,3]; let arr2=[4,5,6]; Array.prototype.push.apply(arr1,arr2); //將arr2合並到了arr1中
6.求數組最大值
Math.max.apply(null,arr)
7.判斷字符類型
Object.prototype.toString.call({})