Extending javascript function with parameters

Asked

Viewed 71 times

0

I wonder if it is possible to extend a javascript function without having to repeat the parameters, as if it were a constructor, I currently use it like this:

function DefaultRun(args1,args2) {
}

function Run(args1, args2){
    DefaultRun.call(this,
        args1,
        args2);
}

Run.prototype = Object.create(DefaultRun.prototype);

There’d be some way to do it?

function DefaultRun(args1, args2, args3) {
}

function Run(){
    DefaultRun.call(this);
}

Run.prototype = Object.create(DefaultRun.prototype);

That is, add an argument in the parent always need to add in all their children. It would be possible?

Edit ----

I need this, because I use this function in several files that have a controller in Angularjs, in this style:

function Run(){
    DefaultRun.call(this, ...arguments);
}

Run.prototype = Object.create(DefaultRun.prototype);

angular.module("APP").run(Run);

However to use the $scope, I need to define this in the Run function, that is, if I need to add some parameter, I will need to add in all the files that use it as Parent.

1 answer

1


In Javascript, when you invoke a function, all arguments are stored in an object/array with the name Arguments, regardless of whether you have declared the parameters or not, so I suppose using DefaultRun.call(this, ...arguments); you would automatically send all arguments to the parent constructor, generating a behavior similar to what you want.

  • That’s the problem, I need to centralize it. The children are called in several places, I need to manage it by the Father.

  • @Kol So neither I nor the colleague who answered we understand your question... Can you please edit your question and inform more details? Explain the use case helps, maybe the solution is different than you imagine.

  • 1

    Unless I have misunderstood, this is exactly what the suggested function does. "..." is the rest operator, it will send the first item of the array as first argument, the second as second, the third as third, and so on. If the parent object is taking too many arguments, I recommend rewriting your constructor to only receive a JSON, so you don’t have to worry about the structure later.

Browser other questions tagged

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