![](/img/trans.png)
[英]Advantages and disadvantages of preventing default event action at start or end of JavaScript function
[英]Advantages and disadvantages of using “()” while calling function in Javascript?
在許多地方有關於JavaScript方法“call”和“apply”的解釋。 但是,我找不到有關使用()
調用函數的任何解釋。 例如:
var a = function(arg){
//arg.call();
//arg.apply();
//arg();
}
var myParam = function() {
//do someting
}
var instance = new a(myParam);
我應該使用哪種方式? 使用()
調用方法有什么缺點?
調用函數有三種方法。
Direct: myFunction(Object arg1, Object arg2, ...);
Call: myFunciton.call(Object this, Object arg1, Object arg2, ...);
Apply: myFunction.apply(Object this, Array args);
每個都有自己的功能。 call()
和apply()
的唯一缺點可能是它們的性能很差。 經過一些研究后發現它們比直接調用函數要慢一點。 雖然這么少,但它甚至不值得考慮。
因為沒有巨大的缺點,我們可以通過判斷優勢來選擇一種方法。 這意味着,比較功能和選擇適合您的情況。
.call();
與直接調用函數不同, .call()
允許您設置this
關鍵字。 除此之外它實際上是一樣的。 那你為什么要設置this
關鍵字呢? 看看下面的例子。
var element = document.getElementById('my-element');
doSomething(element, function(success) {
if(success) {
// something succeeded!
// because I passed "element" as "this",
// I can use "this" to do more stuff with "element"
this.style.display = 'none';
}
});
function doSomething(element, callback) {
// do something with element
// I'm done, let's call the callback
callback.call(element, success);
}
正如您所看到的,回調參數中的this
指的是我們一直在玩的元素。 這就是為什么我們喜歡使用this
因為......這很有意義! 特別是當你使用對象時。
.apply();
就像.call()
非常類似於直接調用函數一樣, .apply()
帶有其他功能。 可以使用數組來定義參數,而不是允許程序員定義一組參數。 這允許您擁有動態數量的參數。
您可能熟悉Math.max()
。 此函數采用未定義數量的參數,並返回最大數字。
Math.max(1, 2, 3); // 3
Math.max(1, 3, 2); // 3
Math.max(1, 2, 3, 2, 3, 1, 2, 3); // 3
如果我們有一系列數字,或許來自一個Feed,我們想得到最大的數字怎么辦? 這顯然有效:
var numbers = [1, 6, 2, 8, 10, 6, 13, 5, 2, 8, 7, 75, 23, 7, 12, 75];
// Prepare "max"
// Anything is greater than -Infinity
var max = -Infinity;
// Loop through all numbers
for(var i = 0; i < numbers.length; i++) {
// Compare current number with existing max
max = Math.max(max, numbers[i]);
}
你浪費寶貴的時間循環遍歷所有數字,同時你可以為你做本機代碼。 這就是.apply()
派上用場的地方。 雖然我們有能力設置this
,但Math.max()
不使用this
關鍵字,所以我們可以丟棄它並使用null
代替。 數組中有多少元素並不重要。
var numbers = [1, 6, 2, 8, 10, 6, 13, 5, 2, 8, 7, 75, 23, 7, 12, 75];
var max = Math.max.apply(null, numbers); // Apply all array elements as an own argument
任何這些方法都沒有(明顯的)缺點。 做任何看起來最適合這種情況或你最喜歡的事情。
如果你並不需要的“功能” .call
或.apply
提供,即設置this
或傳遞的參數數組,那么就沒有必要使用它們。
使用just ()
調用函數是調用函數的“常規”方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.