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);
Mohammad Kermani
  • 4,713
  • 6
  • 35
  • 55

3 Answers3

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));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
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.

Community
  • 1
  • 1
coffee_addict
  • 886
  • 8
  • 15
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
Srinivas Damam
  • 2,728
  • 1
  • 14
  • 25