简体   繁体   English

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

[英]add(a,b) and a.add(b)

how can i transform a method (that performs a+b and returns the result) from add(a,b) to a.add(b)? 如何将方法(执行+ b并返回结果)从add(a,b)转换为a.add(b)?
i read this somewhere and i can't remember what is the technique called... 我在某个地方读到这个,我不记得所谓的技术是什么......
does it depends on the language? 这取决于语言吗?

is this possible in javascript? 这可能在JavaScript中?

In .NET it is called extension methods . 在.NET中,它被称为扩展方法

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

UPDATE: 更新:

In javascript you could do this: 在javascript中你可以这样做:

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

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

On c# it is named extensions methods: 在c#上,它被命名为扩展方法:

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

say for example you want to do this on integers in C#. 比方说,你想在C#中的整数上做这个。 You need to define extension methods like this: 您需要定义这样的extension methods

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

In C# you can use an Extension Method . 在C#中,您可以使用扩展方法 In C++, you need to create a member which belongs to the A class which performs the add for you. 在C ++中,您需要创建一个属于A类的成员,该类为您执行添加。 C does not have objects, so what you're looking for is not possible in C. C没有对象,所以你在C中寻找的东西是不可能的。

If you want to create your own JavaScript class: 如果要创建自己的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);

Taking your question literally, I assume you mean transforming this 从字面上看你的问题,我认为你的意思是改变这个

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

to this: 对此:

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

This however only adds that method to a, not to any other object with the same constructor. 但是,这只会将该方法添加到a,而不是添加到具有相同构造函数的任何其他对象。 See Darin Dimitrov's answer for an example of that. 请参阅Darin Dimitrov的答案。 Extending the native Number constructor's prototype is not something many would recommend though... 扩展本机Number构造函数的原型并不是很多人会推荐的......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM