how can i transform a method (that performs a+b and returns the result) from add(a,b) to a.add(b)?
i read this somewhere and i can't remem开发者_Go百科ber what is the technique called... does it depends on the language?is this possible in javascript?
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 could do this:
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:
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#. You need to define extension methods
like this:
public static class IntExtMethods
{
public static int add(this int a, int b)
{
return a+b;
}
}
In C# you can use an Extension Method. In C++, you need to create a member which belongs to the A class which performs the add for you. C does not have objects, so what you're looking for is not possible in C.
If you want to create your own JavaScript class:
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. See Darin Dimitrov's answer for an example of that. Extending the native Number constructor's prototype is not something many would recommend though...
精彩评论