Javascript prototype inheritance

I took the following example from the book Javascript Good Parts and I ran it in firefox:

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

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

console.log((-10 / 3).integer());

      

This is my understanding of how it works. We use the high precedence operator () to evaluate -10/3, which gives this 64-bit floating point value -3.3 ... Since JavaScript has no Float, Decimal, or Integer types, the return value is Number. Hence, we call the integer () function on the Number object, which is on the prototype chain. "this" must refer to the value that the Number object has. We use triple to check if it's negative or positive, in which case we run: Math'ceil 'since it was negative. This will round the number up to produce -3.

This script will work, but I don't understand why Number.method does not throw an exception, since Number is not a function and method type defined on the function prototype, not a number prototype, and a number does not inherit from Function, it only inherits Object.prototype.

+3


source to share


1 answer


Try these examples on console

Number

is a function.

typeof Number
"function"

      

confirms this.



So Number

inherits fromFunction

Number instanceOf Function
"true"

      

And Function

like all other JavaScript objects, inherits fromObject

Function instanceof Object
true

      

+3


source







All Articles