How to overload method in javascript?

Asked

Viewed 3,726 times

5

Personal how to manage to emulate overload of methods in javascript? I know that some programmers can, for example, I will use Gulp.

Gulp has the 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 rotate the example-task-2, I spin before the example-task, because the example-task-2 is a kind of task dependent on example-task.

Anyway, but this was used only to illustrate what I want to understand. Notice the signature of the method .task

The first parameter is a string, and the second can be an array or an anonymous function. How do I get that? Since I come from JAVA, that would be easy: I would write two methods with the same name and would change only the received parameter, would be 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, as it would be?

2 answers

3

It is commum in flexible Apis functions accept different number and type of parameters. To separate the waters and know who is who in Runtime can inspect the arguments which is a reserved word. At the bottom an array type variable available within the scope of any function.

It could also be so:

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 check if they were passed 3 arguments to the function. I could also do otherwise by iterating the arguments, but you get an idea.

  • Boy, business is nothing trivial then.. Besides a different number of parameters, sometimes we need to filter via types.

  • @user155542 Yes. It is a matter of not creating too many possibilities not to become complex to manage the code.

1

In the javascript you can call the functions even not passing all methods, example:

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 Object...

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.