简体   繁体   中英

To assign a prototype to Number, should I use Function.prototype or Object.prototype?

I want to extend the type 'Number' with a new function and hence I have to define a prototype. When I think about this, I get a bunch of questions:

  1. Does Number inherit from both Object.prototype as well as Function.prototype?
  2. Is 'Number' an 'Object' or a 'Function'?
  3. When should I define an object as a prototype for Number? Does it make sense?

1- True. Number instanceof Object returns true also Function instanceof Object returns true. So Number has all methods that Object and Function has.

2- Number is a function. typeof Number returns "function".

3- If you want to add a method to Number's prototype, just use

Number.prototype.METHOD_NAME = function() {
    // your logic
}

Then you can call your method on all numbers like 1..METHOD_NAME()

The number methods are already contained in Number.prototype to add own methods just do:

Number.prototype.addOne = function(){
return this.valueOf() + 1;
};

1..addOne() // 2

Your question confuses me as I am not sure whether by Number you mean the number constructor which is just an ordinary function or number primitives.

Number primitives are not objects and as such don't inherit anything, when you do 1..addOne() the number is converted to an object and then the .addOne is found in the Number.prototype and called with this set to the object form of the number.

Number itself is an ordinary function.
You can assign properties to it directly.

If you want to extend number instances , you should assign to Number.prototype .

I don't understand your questions. If I really thought monkey-patching Number was a good idea, I'd just do:

Number.prototype.newfunc = function(...) { ... }

Number, Function and Object are all General-purpose constructors. Number inherit from Function which in turn inherits from Object. Number constructor should be used for number primitive to create wrapper object and invoke associated functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM