2014-01-18 96 views
1

要查找的數字在JavaScript中的數組的最低,我們做這樣的事情:爲什麼將Math對象設置爲上下文?

var min_val = Math.min.apply(Math, [12,3,5,7,-1]); 

任何可以想象的原因,你會希望通過這裏的數學對象?

編輯:

還不清楚其中這樣的圖案有意義

FOO .fun.apply(FOO,陣列)

+0

在這種情況下,我認爲不是很有用,您可以通過'0' – elclanrs

+0

可能的重複[Math.min.apply(0,array) - why?](http://stackoverflow.com/ question/2870015/math-min-apply0-array-why) – MT0

回答

1

這裏沒有必要通過Math

回答您的編輯:

還不清楚其中這樣的格局是有道理的:foo.fun.apply(foo, array)

讓我們通過例子來說明:

var foo = { 
      fun: function(a,b,c){ console.log(this.bar, [a,b,c]); }, 
      whatsthis: function(){ console.log(this);}, 
      bar: 5 
      }; 
var bar = {bar: 10}; 
foo.fun.apply(null, [1,2,3]); //=> prints undefined, [1,2,3]. Why? 
foo.whatsthis.apply(null); //=> aha: prints Window 
foo.fun.apply(foo, [1,2,3]); //=> prints 5, [1,2,3] 
// apply foo.fun within bar context: 
foo.fun.apply(bar, [1,2,3]); //=> prints 10, [1,2,3] 

所以,foo.fun.apply在執行foo.fun全球範圍(window),因此將需要一個上下文(s應對)能夠引用上下文的屬性(foobar)。

1

Math.min內部實現可以使用this 。所以最好保留它。 AFIK,document.getElementById(以及其他人)的情況:您不能僅僅執行$ = document.getElementById,我在調用它時會拋出TypeError: Illegal invocation

+2

1)什麼? 2)除非文件說明如此,否則不得考慮任何「內部」細節。 –

+0

@ OlegV.Volkov,所以你知道所有這些文檔細節?至於我,在正確的上下文中調用'apply'比記住要容易得多(或者在編碼時去檢查它)。 –

+0

爲什麼ECMAScript標準版5的第15.8.2.12節會告訴你有關'Math.min'的所有信息。說沒有在那裏或在特定的環境發佈說明中提到的任何事情都會傳播錯誤信息,因爲沒有很好的理由。 –

0

第一個參數是,在這種情況下,任意的:

console.log(Math.min.apply(Math, [12,3,5,7,-1])); 
console.log(Math.min.apply(null, [12,3,5,7,-1])); 
console.log(Math.min.apply(0, [12,3,5,7,-1])); 
console.log(Math.min.apply(undefined, [12,3,5,7,-1])); 
console.log(Math.min.apply(-10, [12,3,5,7,-1])); 

所有上述輸出-1

因此,在這種情況下沒有特別的理由通過Math對象。

編輯

圖案foo.fun.apply(foo, array)從一個函數傳遞參數時到另一個有意義的:

wrapper = function(){ 
    // call foo.fun() with the same arguments as were 
    // passed to the wrapper function. 
    var rtn = foo.fun.apply(foo, arguments); 

    // do something with the return value. 
} 

也可以使用它動態地定義所述參數的函數時(該例子是一個很少做作,但希望它給你的想法):

var values = [], 
    foo = { 
     set: function(){ this.inputs = Array.prototype.slice.call(arguments, 0); }, 
     sum: function(){ 
      var i=0,total=0; 
      for (; i < this.inputs.length; ++i) 
       total += this.inputs[i]; 
      return total; 
      }, 
     inputs: [] 
    }; 

console.log(foo.sum()); // Outputs 0 

// Get user to add values from somewhere (i.e. a HTML input field) 
values.push(1); 
values.push(2); 
// Once finished call foo.set 
foo.set.apply(foo, values); 

console.log(foo.sum()); // Outputs 3 
0

短回答因爲你必須這樣做。 Apply將方法的上下文作爲第一個參數。我相信Math.min也是在全球範圍內都有效,所以你可以寫

Math.min.apply(null,[12,3,5,7,-1]); 

還有其他方法來寫不要​​求你這樣做(例如,你可以只寫Math.min( [12,3,5,7,-1])),但這一切都取決於你在做什麼。

你可以找到更多關於適用和上下文here的細節。

+0

'Math.min([12,3,5,7,-1])'''NaN' – MT0

+0

糟糕,你是對的。這應該是Math.min(12,3,5,7,-1)。沒有方括號。 Math.min期望參數是一個或多個數字,而不是數組。 – KyleW

相關問題