我正在阅读这本书Javascript: the Good Parts。当我阅读下面的代码时,我有点困惑:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Number.method('integer',function(){
return Math[this < 0 ? 'ceil' : 'floor'](this);
});
我认为上面代码的第一部分意味着 JavaScript 中的任何函数现在都有一个名为method的方法。但是“数字”也是一个函数吗?为什么Number.method有意义?
我假设 Number 继承了 Number.prototype 继承了 Object.prototype(Number->Number.prototype->Object.prototype),因为 Number 一开始没有“方法”方法,它会沿着原型链寻找它。但是 Function.prototype 不在链上,对吧?
Number、Number.prototype 和 Function.prototype 之间的关系是什么?
更新我:
我已经搜索了一些额外的信息,现在更加困惑。有人说 Number 实际上是一个函数,这似乎是有道理的,因为Number instanceof Functionistrue的值。但是 is 的(-10 / 3) instanceof Number值false。这不是很混乱吗?如果数学中的数字(例如 3、2.5、(-10 / 3))Number在 JavaScript 中甚至不是 a,那么如何(-10 / 3)调用integer()from 中的方法Number?(下面一行来自同一本书)
document.writeln((-10 / 3).integer());
更新二:
问题基本解决了。
感谢@Xophmeister 的帮助,现在我的结论是Number可以调用method,因为Number它是一个构造函数,因此它链接到Function.prototype. 至于为什么 JavaScript 中类型为原始类型的 number(3, 2.5, (-10 / 3)) 可以调用 objectNumber具有的方法,请参考此页。
我基本上从@Xophmeister 的帮助和一些搜索中得到了这个结论,所以它可能不够精确。欢迎任何更正或完成。