Methods with the same name but with different number of parameters [duplicate]

3

In C # or Java in a class I can define methods with the same name but with different variables, like this:

//em C#
public class Classe {
    public String teste(String hello, String world){
        return  hello + world;
    }
    public String teste(String full){
        return full;
    }
    public String teste(){
       return "hello world";
    }
}

I need to know how I could generate methods with that same sense where the method name is the same but depending on the elements I submit it will process a block of code or another ...

    
asked by anonymous 08.04.2016 / 05:16

3 answers

9

What is done in javascript in this respect is to create a function and, at the beginning of the function implementation, to analyze and treat the arguments so that it can be used in a more dynamic way. When defining a function twice javascript overrides the first implementation of the function, you have no immutability.

A function that would translate the functionality you are looking for, written in javascript, would look like this:

function teste() {
  if(arguments.length === 0)
    return "hello world"

  if(arguments.length === 1 &&
    typeof(arguments[0]) === 'string')
    return arguments[0];

  if(arguments.length === 2 &&
    typeof(arguments[0]) === 'string' &&
    typeof(arguments[1]) === 'string')
    return arguments[0] + arguments[1];
}

// Para casos tratados
teste(); // "hello world"
teste("teste1"); // "teste1"
teste("teste1", "teste2"); // "teste1teste2"

// Para casos não tratados
// Quando uma função não retorna, explicitamente, nenhum valor, você recebe undefined
teste("teste1", "teste2", "teste3"); // undefined
teste(1); // undefined
teste("teste1", 1); // undefined

Within the scope of every function you can access the variable arguments . This variable represents an object whose indexes are numbers, starting at zero. I think this is the key to solving your problem.

Ex:

// arguments = {length: 0}
teste();

// arguments = {length: 1, 0: "teste1"}
teste("teste1");

// arguments = {length: 2, 0: "teste1", 1: "teste2"}
teste("teste1", "teste2");

// arguments = {length: 3, 0: "teste1", 1: "teste2", 2: "teste3"}
teste("teste1", "teste2", "teste3");

// arguments = {length: 1, 0: 1}
teste(1);

teste("teste1", 1); // arguments = {length: 2, 0: "teste1", 1: 1}
    
08.04.2016 / 06:10
5

This is called method overloading . No, this is not possible in the way you want to do in JavaScript.

However, JavaScript does not reject the passing of a number of parameters other than what is declared in the function signature. If you have a function

function funcaoComAridade2(parametro1, parametro2) {
    console.log("Primeiro: " + parametro1);
    console.log("Segundo: " + parametro2);
}

Nothing prevents you from calling it like this:

funcaoComAridade2(33);

The only problem is that parametro2 will get the value undefined .

You can even find out the number of parameters passed. Just get the size ( length ) of the style-vector object arguments within the function. This object contains the received parameters, no matter how many. You can rely on this to decide, in the body of the method, which way to go.

    
08.04.2016 / 05:42
3

Actually they are different parameters. This is called overloading (overload).

In JavaScript this is not possible because it does not have the resource mentioned, it has to have something in the name to differentiate one from the other. Try to find a suggestive name that indicates the difference, if you can not tell the difference by specifying the type (s) in the name, but try to make it as intuitive as possible.

In fact this would not be possible since JavaScript does not have static types, at least until the current version, which makes the decision difficult.

What is possible is to simulate this with checks inside the function body. That is, you would only have one function accepting several parameters. Inside would have some ifs analyzing the amount of parameters actually passed and possibly the type of each one of them. The decision that parts of the function (or delegate to others) should be performed will proceed from what has been decided there. There are other techniques passing objects or using default arguments technique.

Examples written by John Resig . See question about the theme with more examples.

In dynamic languages several mechanisms need to be written by the programmer.

Same TypeScript ( more info ) that has types do not have the ability to decide by type. If it did this would have complications to generate the source JS. It is able to decide only by the amount of parameters.

    
08.04.2016 / 05:39