Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the relationship between Number and Function.prototype in javascript?

I'm reading the book Javascript: the Good Parts. I'm a little confused when I read the code below:

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

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

I think the first part of code above means that any function in JavaScript now has a method called method. But is "Number" also a function? Why does Number.method make sense ?

I suppose that Number inherits Number.prototype which inherits Object.prototype(Number->Number.prototype->Object.prototype), since Number has no "method" method at the beginning, it will look for it along the prototype chain. But Function.prototype isn't on the chain, right?

What's the relationship among Number, Number.prototype and Function.prototype?


UPDATE I:

I've searched for some extra information and am more confused now. Some say that Number is in fact a function and this seems to make sense because the value of Number instanceof Function is true.But the value of (-10 / 3) instanceof Number is false. Isn't this confusing? If a number in math (such as 3, 2.5, (-10 / 3)) is not even a Number in JavaScript, how can (-10 / 3) invoke integer() which is a method from Number? (The line below comes from the same book)

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

UPDATE II:

Problem solved, basically.

Thanks to @Xophmeister's help, now my conclusion is that Number can invoke method because Number is a constructor so that it is linked to Function.prototype. As for why a number(3, 2.5, (-10 / 3)) whose type is primitive type in JavaScript can invoke a method that object Number has, one should refer to this page.

I got this conclusion basically from @Xophmeister's help and a little search so it may not be precise enough. Any correction or completion is welcomed.

like image 724
ChandlerQ Avatar asked Mar 27 '13 10:03

ChandlerQ


1 Answers

I believe the prototype chain is: Object > Function > Number:

Number instanceof Function; // true
Number instanceof Object;   // true
Function instanceof Object; // true
like image 50
Xophmeister Avatar answered Oct 01 '22 12:10

Xophmeister