添加(a,b)和a.add(b)

时间:2010-04-22 11:45:34

标签: c# javascript c++ c

如何将方法(执行+ b并返回结果)从add(a,b)变换为a.add(b)?
我在某个地方读到这个,我不记得所谓的技术是什么...
这取决于语言吗?

这可以在javascript中使用吗?

6 个答案:

答案 0 :(得分:13)

在.NET中,它被称为extension methods

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

更新:

在javascript中你可以这样做:

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

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

答案 1 :(得分:1)

在c#上,它被命名为扩展方法:

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

答案 2 :(得分:1)

例如,你想在C#中对整数执行此操作。您需要像这样定义extension methods

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

答案 3 :(得分:0)

在C#中,您可以使用Extension Method。在C ++中,您需要创建一个属于A类的成员,该类为您执行添加。 C没有对象,所以你在C中找不到你想要的东西。

答案 4 :(得分: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);

答案 5 :(得分:0)

从字面上理解你的问题,我认为你的意思是改变这个

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

到此:

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

然而,这仅将该方法添加到a,而不是添加到具有相同构造函数的任何其他对象。请参阅Darin Dimitrov的答案。扩展本机Number构造函数的原型并不是很多人会推荐的......