How to do method overload in javascript?

5

Personnel how to emulate method overload in javascript ? I know some programmers can, for example, I'm going to use gulp.

gulp has method .task :

var gulp = require('gulp');

gulp.task('example-task', function(){
    console.log('running example-task')
})

gulp.task('example-task-2', ['example-task'], function(){
    console.log('running example-task')
})

But if I want to run some tasks before others, I do this:

var gulp = require('gulp');

gulp.task('example-task', function(){
    console.log('running example-task')
})

gulp.task('example-task-2', ['example-task'], function(){
    console.log('running example-task')
})

When I want to run example-task-2 , I first run example-task because example-task-2 is a kind of task dependent on example-task .

Anyway, this was just used to exemplify what I want to understand. Perceive the signature of method .task

The first parameter is string , and the second can be an array or an anonymous function. How can I get this? As I come from JAVA, this would be easy: I would write two methods with the same name and would only change the parameter received, it would look something like this:

public interface Gulp {
    public void task(String taskName, AnonymousFunction run);
    public void task(String taskName, List<Task> depencencies, AnonymousFunction run);
}

And in js, what would it be like?

    
asked by anonymous 15.01.2016 / 21:35

2 answers

3

It is common in flexible APIs that the functions accept different number and type of parameters. To separate the waters and to know who is who in runtime can inspect the arguments which is a reserved word. In the background an array type variable available within the scope of any function.

It could also be:

function foo(){
    var fn, str, arr;
    if (typeof arguments[2] != 'undefined'){
        fn = arguments[2];
        arr = arguments[1]
    } else {
        fn = arguments[1];
    }
    // aqui podes fazer algo com fn, str e arr. Sendo que caso "!arr == true" então ela não foi passada à função
}

In this example, I checked if 3 arguments were passed to the function. It would also be possible to do otherwise by iterating arguments , but you have a judging idea.

    
15.01.2016 / 21:59
1

In% w / w you can call the functions even if you do not pass all methods, eg

function foo(param1, param2) {
    console.log(param1);
    console.log(param2);
}

If you call

foo(); // mostra undefined e undefined 
foo(1); // mostra 1 e undefined
foo(1, 2); // mostra 1 e 2

However, you can do something similar to javascript

function foo() {
    for (var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
 }
    
15.01.2016 / 21:40