3

Imagine I have this function:

function test(firstNumber,SecondNumber){
  return (firstNumber*secondNumber);
}

I want to do the same function (the above function) in a different way like bellow and I want to know how is it possible in JavaScript:

var firstNumber= 10; //some number;
firstNumber.test(secondNumber);

3 Answers 3

9

You could use a custom prototype of Number for it.

Number.prototype.test = function (n) {
    return this * n;
}

var firstNumber = 10; //some number;
document.write(firstNumber.test(15));

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

Comments

4

You can extend the Number object with your own functions.

Number.prototype.test = function (other) {
    return this.valueOf() * other;
};

var firstNumber = 10;
var secondNumber = 10;

firstNumber.test(secondNumber);

Please keep in mind that extending native Javascript objects is a bad practice.

Comments

1

Just some other way instead of extending native javascript objects

var utils = {
  add: function(a, b) {
   return (a + b)
  }
}

var one = 1
var two = 2

utils.add(1, 2) // prints 3

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.