1

So I know I can do this...

Number.prototype.square = function () { return this * this }
 [Function]
4..square()
 16

Is there a way to inherit from the Number function so that I don't have to modify the Number prototype? With a function or object, I can inherit like this...

var NewObject = new Object()
var NewFunction = new Function()

Is there a was to do something similar w/ Number?

2
  • The question is not clear :-/ Commented Sep 23, 2014 at 14:10
  • I edited the question for clarity. Commented Sep 23, 2014 at 14:18

2 Answers 2

3

Yes, you can easily inherit from the Number.prototype. The trick is to make your objects convertible to numbers by giving them a .valueOf method:

function NumLib(n) {
    if (!(this instanceof NumLib)) return new NumLib(n);
    this.valueOf = function() {
        return n;
    }
}
NumLib.prototype = Object.create(Number.prototype);
NumLib.prototype.square = function () { return this * this }

The cast will happen whenever a mathematical operation is applied to the object, see also this answer. The native Number methods don't really like to be called on derived objects, though.

Sign up to request clarification or add additional context in comments.

Comments

1

using Object.defineProperty allows you to have a little more control over the object.

Object.defineProperty(Number.prototype,'square',{value:function(){
 return this*this
},writable:false,enumerable:false});
//(5).square();

with your own lib it's the same...

Object.defineProperty(NumLib.prototype,'square',{value:function(){
 return this.whatever*this.whatever
},writable:false,enumerable:false});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.