【发布时间】:2014-01-24 00:08:40
【问题描述】:
刚读完“JavaScript: The Good Parts”——很棒的书。但是我对第 33-34 页上的一个非常重要的主题感到困惑 - 增强类型。它描述了添加到 Function.prototype 的新方法的创建,因此当使用新方法调用时,所有函数都将具有该方法可用。很公平。但随后的示例显示此方法用于数字和字符串。我在想,是对象而不是函数。我在这里错过了什么?
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
使用示例:
Number.method('integer', function() {
return Math[this < 0 ? 'ceiling' : 'floor'](this);
});
document.writeln((-10 / 3).integer()); //-3
【问题讨论】:
-
函数是对象。
-
@MattBall 我认为这不是 OP 的要求。相反,我认为他/她在问
Number是如何从Function派生的。 -
数字是一个函数。它不是从函数“派生”出来的。这是一个实例。
-
@Pointy, Object.getPrototypeOf(Number) == Function.prototype // true
-
@JukkaP 没错,就是一个 Function 实例。
标签: javascript