我正在閱讀「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
在這種情況下,它是否意味着(-10/3)是一個對象,然後我在對象上調用函數'integer',當我在該對象上調用函數時,'this'關鍵字將指向該對象,因此,數學[ceil |地板]'得到對象的參考,即(-10/3)。我的理解是否正確?請給出意見。 – zilcuanu
是的,除了(-10/3)實際上是一個原語,一切都是正確的,但是當你嘗試調用它的一個方法時,javascript會將它包裝爲Number(-10/3),這是一個真正的對象。 – Quarter2Twelve
爲我學習更多。當我們調用2.toString()時,我們會得到一個錯誤,它被視爲原始的,而當我們調用(2).toString()時,我們得到「2」。我的假設是把一個數字放在括號內被視爲一個對象,而只是調用2.toString()被視爲原始正確的? – zilcuanu