Garret Schweitzer
Garret Schweitzer

Reputation:

Functions as parameters (with parameters) -- JavaScript

If I have some OO javascript that looks like so:

function someFunction(a, b, c) {
  // do something with a, b, and c
}

function theLoader() {
    loadFunction: someFunction,
    load: function() {
      // invoke the loadFunction with the proper parameter set
    }
}

var myLoader = new theLoader();
myLoader.load();

Let's assume that 'theLoader' is expected to be abstract and generic. I could call it and set the 'loadFunction' to almost anything, so I don't know what the arguments are going to be at any given time. The 'load' method must invoke the 'loadFunction' and somehow be able to get an argument set to it....

How can I accomplish what I'm trying to do? If this is a bad way to go about it, we can totally refactor the code. I'd like to keep restrictions off of the 'loadFunction' so I don't have to code loader functions in a special way.

At the end of the day, I'd like to package theLoader into it's own .js file and not have to monkey with it.

So -- if you know the answer, help a brother out!!

Thanks, g

Upvotes: 3

Views: 360

Answers (3)

Helgi
Helgi

Reputation: 1577

I think what you're looking for is this:

function theLoader() {
    this.load = function() {
        if (this.loadFunction) {
            return this.loadFunction.apply(this, arguments);
        }
    };
}
// Usage
var loader = new Loader();
loader.loadFunction = someFunction;
loader.load(1, 2, 3, 4);

Also, you were mixing object literal notation with function literals, which is incorrect.

Upvotes: 0

TheHippo
TheHippo

Reputation: 63139

Use apply or call to perform the function call. A description of the functions can be found here:

Upvotes: 3

Crescent Fresh
Crescent Fresh

Reputation: 116980

You should make your loadFunction follow an interface, and use polymorphism to call it. Having said that, you do have a real requirement to capture the arguments to someFunction in some way.

Can you allow the load function to take the parameters that loadFunction requires?

myLoader.load(1, '2', 'foo'); // calls this.loadFunction(1, '2', 'foo')

Or, allow theLoader to take them in the constructor?

function theLoader() {
    this.loadFunctionArgs = arguments;
}

theLoader.prototype = {
    loadFunction: someFunction,
    load: function() {
        return this.loadFunction.apply(this, this.loadFunctionArgs)
    }
}

var myLoader = new theLoader(1, '2', 'foo');
myLoader.load(); // calls someFunction(1, '2', 'foo')

I haven't the slightest idea if this is a good design for your app. It's certainly ok to do in JavaScript (as far as the language goes I mean).

Upvotes: 1

Related Questions