js中的apply與call的用法

2021-07-30 00:18:33 字數 2156 閱讀 6115

var test = function

()test.call(undefined);//true

用法

此時foo中的logname方法將被bar引用 ,this指向了bar

var foo = 

}var bar=;

foo.logname.call(bar);//xiaowang

function

animal

(name)

}

function

cat(name)

var cat = new cat("black cat");

cat.showname(); //black cat

在實際開發中,經常會遇到this指向被不經意改變的場景。

有乙個區域性的fun方法,fun被作為普通函式呼叫時,fun內部的this指向了window,但我們往往是想讓它指向該#test節點,見如下**:

window.id="window";

document.queryselector('#test').onclick = function

() fun();//window

}

window.id="window";

document.queryselector('#test').onclick = function

() fun.call(this);//test

}

當然你也可以這樣做,不過在ecmascript 5的strict模式下,這種情況下的this已經被規定為不會指向全域性物件,而是undefined:

window.id="window";

document.queryselector('#test').onclick = function

() fun();//test

}function

func

()func();

其他用法

這裡把符合以下條件的物件稱為類陣列

1.具有length屬性

2.按索引方式儲存資料

3.不具有陣列的push,pop等方法

常見類陣列有 arguments,nodelist!

(function

())(1,2,3)

這樣就往arguments中push乙個4進去了

array.prototype.push 頁可以實現兩個陣列合併

var arr1=new

array("1","2","3");

var arr2=new

array("4","5","6");

console.log(arr1);//["1", "2", "3", "4", "5", "6"]

再比如我想求類陣列中的最大值

(function

())(34,2,56)

;

判斷型別

console.log(object.prototype.tostring.call(123)) //[object number]

console.log(object.prototype.tostring.call('123')) //[object string]

console.log(object.prototype.tostring.call(undefined)) //[object undefined]

console.log(object.prototype.tostring.call(true)) //[object boolean]

console.log(object.prototype.tostring.call({})) //[object object]

console.log(object.prototype.tostring.call()) //[object array]

console.log(object.prototype.tostring.call(function

(){})) //[object function]

js中call與apply的應用

call方法的官方解釋為 呼叫乙個物件的乙個方法,以另乙個物件替換當前物件。call thisobj arg1 arg2 argn 引數thisobj可選項。將被用作當前物件的物件。arg1,arg2,argn可選項。將被傳遞方法引數序列。說明call 方法可以用來代替另乙個物件呼叫乙個方法。cal...

js中的call與apply用法

call 方法 呼叫乙個物件的乙個方法,以另乙個物件替換當前物件。call thisobj arg1 arg2 argn 引數 thisobj 可選項。將被用作當前物件的物件。arg1,arg2,argn 可選項。將被傳遞方法引數序列。說明 call 方法可以用來代替另乙個物件呼叫乙個方法。call...

js中call 與apply 的用法

functionname.call obj arg1,arg2.call 可以用來代替另乙個物件呼叫某個方法。如果沒有提供obj引數,則obj為全域性物件 即為this值 例子如 function add a,b function sub a,b add.call sub,3,1 這個例子的結果為4...