javascript 函数调用的解释

explanation on javascript function call passing this

我正在阅读 "Javascript the Good Parts" 这本书并尝试通过示例来理解这些概念。我遇到了一个例子,但无法理解。请查看下面的代码,让我了解我哪里出错了:

//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);

我知道我的方法行不通,但很难找到原因。请给我更新一些例子来强化概念。

将 link 分享给 Fiddle - Fiddle - link

According to my understanding the calling function should be something like (-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 函数中看出。

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

所以您添加到 Number 的方法将 return 一个函数而不是一个值。

虽然在行尾添加 (this) 将使用调用者的值调用此函数,在您的情况下为 -10/3。所以它将return给你的期望值。