Add (a, b) and a.add (b)

how can I convert a method (which does a + b and returns the result) from add (a, b) to a.add (b)?
I read it somewhere, and I can’t remember what a technique called ... does it depend on the language?

is this possible in javascript?

+3
source share
6 answers

In .NET, it is called extension methods .

public static NumberExtensions
{
    public static int Add(this int a, int b)
    {
        return a + b;
    }
}

UPDATE:

In javascript you can do this:

Number.prototype.add = function(b) {
    return this + b;
};

var a = 1;
var b = 2;
var c = a.add(b);
+13
source

In C #, it is called extension methods:

public static class IntExt
{
    public static int Add(this int a, int b)
    {
        return a + b;
    }
}
...
int c = a.Add(b);
+1
source

, , #. extension methods :

public static class IntExtMethods
{
    public static int add(this int a, int b)
    {
        return a+b;
    }
}
+1

# . ++ , A, . C , , , C.

0

JavaScript:

function Num(v) {
    this.val = v;
}
Num.prototype = {
    add: function (n) {
        return new Num(this.val + n.val);
    }
};

var a = new Num(1);
var b = new Num(2);
var c = a.add(b); // returns new Num(3);
0

, ,

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

:

a.add = function(b) {
  return this + b;
}

a, . . . Number , ...

0

Source: https://habr.com/ru/post/1742265/


All Articles