Reza
Reza

Reputation: 3949

How to pass an object's method as a parameter to another function in Javascript

First take a look at my simple codes below:

function mySecondFunction(objArray,setFunc)
{
    for (let i = 0; i < objArray.length; i++)
    {
        objArray[i].info.setTop(72);
    }
}

function myFunction()
{
    let myObjArray = [];
    for (let i = 0; i < 10; i++)
    {
    myObjArray.push({
        info:{topVar:0,
          bottomVar:0,
          get top() {return this.topVar;},
          get bottom() {return this.bottomVar;},
          setTop: function(input) {this.topVar = input;},
          setBottom: function(input) {this.bottomVar = input; }
         }
    });
    }
    mySecondFunction(myObjArray); // This works Fine
    mySecondFunction(myObjArray,setTop); // I want something like this!!!
}

As you can see, I want to pass a method of an object to another function. I know a lot of possible solutions to avoid this, but I want to know whether it is possible or not.

Upvotes: 0

Views: 376

Answers (2)

Kevin Qian
Kevin Qian

Reputation: 2720

Detach it and pass as an argument. Remember to use call to set the intended this value.

function mySecondFunction(objArray, setFunc)
{
    for (let i = 0; i < objArray.length; i++)
    {
        setFunc.call(objArray[i].info, 72); 
        /* explicitly telling that: 
        please set 'this' value in this function to be 'objArray[i].info' when running, 
        allowing, e.g. `this.topVar` in 
        `setTop: function(input) {this.topVar = input;}` 
        to be operating on `objArray[i].info.topVar` */
    }
}

function myFunction()
{
    let myObjArray = [];
    for (let i = 0; i < 10; i++)
    {
    myObjArray.push({
        info:{topVar:0,
          bottomVar:0,
          get top() {return this.topVar;},
          get bottom() {return this.bottomVar;},
          setTop: function(input) {this.topVar = input;},
          setBottom: function(input) {this.bottomVar = input; }
         }
    });
    }
    mySecondFunction(myObjArray, myObjArray[0].info.setTop); 
    /* once detaching the method from the object, 
    (if we are not using arrow functions), 
    we lose 'this' value, meaning we are losing 
    the target of object that we want to operate on */
    
    console.log(myObjArray)
}

myFunction();

Upvotes: 5

wmash
wmash

Reputation: 4202

You can target item number in the array list. You can do statically (i.e. 1-???) or dynamically with an iteration and a variable. You can then the object property within that. For example:

myObjArray[0].info.setTop

That will target the 1st item in the array. Be sure to omit parentheses (()) when passing the method as you want to pass the function reference not the result

Upvotes: 0

Related Questions