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
  • 5,188
  • 7
  • 37
  • 61

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
  • 376,160
  • 25
  • 347
  • 392
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
  • 926
  • 9
  • 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,893
  • 2
  • 17
  • 26