FatalKeystroke FatalKeystroke - 3 months ago 11
Javascript Question

Javascript function calling members of parameter objects

Javascript:

var myfunc = function(foo, bar) {
foo.thing();
bar.stuff();
};


if
foo
and
bar
will always be objects with functions
thing
and
stuff
, but
foo
and
bar
have not been declared as global variables because they could be any of a number of objects meeting this criteria, what is the proper way to declare
myfunc
?

And what if
myfunc
is a member of another object?

EDIT
Less generic case (node.js/express):

var express = require("express");
app = express();
app.set("views", __dirname + "html");

var myfunc = function(req, res) {
res.render("file.html");
};

app.get("/", function(req, res) {
myfunc(req, res);
});
// ^ OR v Tried both, but it doesn't get this far
app.get("/", myfunc(req, res));

app.listen(8080);


Errors state in
var myfunc = function(req, res) {
that
res.render()
is undefined.

Answer

EDIT: Specific Case

Change app.get("/", myfunc(req, res)); to app.get("/", myfunc);. This will run the function correctly.

Also, I believe app.set("views", __dirname + "html"); should be app.set("views", __dirname + "/html"); if the folder html exists inside the current directory.

Full Answer

JavaScript is Dynamically Typed

What you have there is perfectly fine. It is not necessary to have the foo and bar objects declared when you declare the myfunc() function.

However, you will have some issues if someone passes objects to myfunc that don't have the thing and stuff methods. So in order to avoid errors, there are a couple ways you can check.

Validate Methods

The first is to see if the objects have the proper methods:

var myfunc = function(foo, bar) {
    if (typeof foo.thing === 'function')
        foo.thing();
    if (typeof bar.stuff === 'function')
        bar.stuff();
};

Validate Object Instsance

You can also make sure that the objects are instances of the required class:

var Qux = function() {
    return {
        thing: function() {
            console.log('I am a thing!');
        },
        stuff: function() {
            console.log('Yikes! That\'s a bunch of stuff');
        }
    };
};

var foo = new Qux();
var bar = new Qux();

var myfunc = function(foo, bar) {
    if (foo instanceof Qux)
        foo.thing();
    if (bar instanceof Qux)
        bar.stuff();
};

myfunc(foo,bar);