2016-02-04 78 views
0

我正在閱讀「JavaScript的好部分」一書,並嘗試通過示例來理解這些概念。我遇到了一個例子,無法理解。請看下面的代碼,讓我明白的地方,我錯了:javascript函數調用通過此說明

//Augmenting the Function prototype with method 
Function.prototype.method = function(name, func){ 
    if (typeof this.prototype[name] !== "function"){ 
     this.prototype[name]=func; 
    return this; 
    } 
} 

// why do we have the (this) at the end of the return statement. 
/*Number.method("integer", function(){ 
    return Math[this < 0 ? 'ceil': 'floor'](this); 
});*/ 

//According to me the function should have been like below: 
Number.method("integer", function(val){ // we get a function and we need to pass the value and the value will be evaluated and returned. 
    return Math[val < 0 ? 'ceil': 'floor']; 
}); 
//According to my understanding the calling function should be something like below. 
alert((-10/3).integer(-10/3); 

我知道我的做法是行不通的,但發現很難得到的理由。請用一些示例來更新我,以強化這些概念。

共享鏈接小提琴 - Fiddle - link

回答

1

Math[val < 0 ? 'ceil': 'floor']是一個函數。想想Math.ceilMath.floor

因此,您添加到Number的方法將返回一個函數而不是一個值。

雖然在行尾添加(this)會調用此函數的調用者的值,在你的情況下-10/3。所以它會將預期值返回給你。

+0

在這種情況下,它是否意味着(-10/3)是一個對象,然後我在對象上調用函數'integer',當我在該對象上調用函數時,'this'關鍵字將指向該對象,因此,數學[ceil |地板]'得到對象的參考,即(-10/3)。我的理解是否正確?請給出意見。 – zilcuanu

+1

是的,除了(-10/3)實際上是一個原語,一切都是正確的,但是當你嘗試調用它的一個方法時,javascript會將它包裝爲Number(-10/3),這是一個真正的對象。 – Quarter2Twelve

+0

爲我學習更多。當我們調用2.toString()時,我們會得到一個錯誤,它被視爲原始的,而當我們調用(2).toString()時,我們得到「2」。我的假設是把一個數字放在括號內被視爲一個對象,而只是調用2.toString()被視爲原始正確的? – zilcuanu

1

根據我的理解調用函數應該像(-10/3).integer(-10/3)

這就是你的誤解是。爲什麼你需要重複這個數字?不,方法應該被稱爲

(-10/3).integer() // -3 

不帶任何參數 - 它作用於值是Number實例(this的方法)。

如果你要作爲參數傳遞的數量,就沒有必要讓它的方法,而應該是一個靜態函數:

Number.integer = function(val) { 
    return Math[val < 0 ? 'ceil': 'floor'](val); 
//           ^^^ still passing it here, of course 
}; 
Number.integer(-10/3) // -3 

這就是可行的爲好,特別是當參數不能保證是一個數字,正如可以通過各種靜態NumberMath函數看到的那樣。