2013-03-27 54 views
6

我在阅读这本书Javascript:好的部分。我有点困惑,当我读到下面的代码:在JavaScript中Number和Function.prototype之间的关系是什么?

Function.prototype.method = function (name, func) { 
    this.prototype[name] = func; 
    return this; 
}; 

Number.method('integer',function(){ 
    return Math[this < 0 ? 'ceil' : 'floor'](this); 
}); 

我觉得上面的代码中的第一部分是指在JavaScript中任何函数现在有一个名为方法方法。但是“数字”也是一个函数吗?为什么Number.method有意义?

我想,Number继承的Number.prototype继承Object.prototype(Number-> Number.prototype-> Object.prototype),因为Number在开始时没有“method”方法,它会沿着原型链。但是Function.prototype不在链上,对吗?

Number,Number.prototype和Function.prototype之间的关系是什么?


更新我:

我搜索了一些额外的信息和现在比较迷茫。有人说,Number实际上是一个函数,这似乎是有道理的,因为Number instanceof Function的值是true。但是(-10/3) instanceof Number的值是false。这不是令人困惑吗?如果数学中的数字(例如3,2.5,( - 10/3))甚至不是JavaScript中的Number,那么(-10/3)如何调用integer()这是一种来自Number的方法? (下面的线来自同一本书)

document.writeln((-10/3).integer()); 

UPDATE II:

问题解决了,基本上。

感谢@ Xophmeister的帮助,现在我的结论是,Number可以调用method因为Number是如此,它链接到Function.prototype构造。至于为什么在JavaScript中基本类型的数字(3,2.5,( - 10/3))可以调用对象Number所具有的方法,则应参考this page

我基本上从@ Xophmeister的帮助和一点搜索得到了这个结论,所以它可能不够精确。欢迎任何更正或完成。

+0

(-10/3)是一个数字,但不是一个号码。 – simon 2013-03-27 11:22:39

+0

@simon但是在'Number'中定义了'integer()'方法,对吧?如果(-10/3)不是'Number',为什么它可以调用'integer()'? – ChandlerQ 2013-03-27 11:34:48

+0

'-10/3'不是'Number' *对象*,而是* type *'number'。我认为ECMA262规范的第8.6.2和9.9节与此相关;特别是JS的[[[PrimitiveValue]]和'ToObject'内部。这篇博客文章可能会更好地解释一些事情:http://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/ – Xophmeister 2013-03-27 12:16:58

回答

3

相信原型链是:Object>Function>Number

Number instanceof Function; // true 
Number instanceof Object; // true 
Function instanceof Object; // true 
+0

'Object instanceof Function'也返回'true'。 – 2013-03-27 10:50:40

+0

我猜这是因为函数是JavaScript中的一等公民。 – Xophmeister 2013-03-27 10:53:19

+0

就像@ neustroev.ai所说的那样,'Object instanceof Function'是'true'。这是否意味着JavaScript中的所有对象都是一个函数? – ChandlerQ 2013-03-27 11:18:11

相关问题