0

I was wondering if it's possible to alter the return value of a function, i.e:

var foo = function(options) {
  var options = options || {},
      bar = options.bar || "bar",
      baz = options.baz || "baz";

  return {
    bar: bar,
    baz: baz
  }
};

I would like to call it like this:

foo({
  bar: this.bar + "ret"
});

And my expectation is:

>>> { bar: "barret", baz: "baz" }

But I get this instead:

>>> { bar: "undefinedret", baz: "baz" }

How do we do that?

Simone
  • 17,439
  • 10
  • 67
  • 96
  • `this` does not work like you expect. Please, refer to (this)[http://stackoverflow.com/questions/3127429/javascript-this-keyword] question. `var obj = foo(); obj.bar += "ret";` – zaquest Sep 28 '13 at 10:19
  • What you expect `this` is in the function call `bar: this.bar + "ret"`? – Sergio Sep 28 '13 at 10:20

3 Answers3

2

Looks like a scoping issue. The this isn't referring to the scope of foo.

This works:

foo({
  bar: foo().bar + "ret"
});
Benjamin Warren
  • 509
  • 4
  • 5
1

Outside function body, this isn't available, so your example fails. You could call:

foo({
    bar: "barret"
});

or (if you do not want to use default value outside of function):

var x = foo();
x.bar += "ret";

or change your function adding one more parameter:

var foo = function(options) {
  var options = options || {},
      bar = options.bar || "bar",
      baz = options.baz || "baz",
      barSuffix = options.barSuffix || "";

  return {
    bar: bar + barSuffix,
    baz: baz
  }
};

foo({barSuffix: "ret"});
el.pescado
  • 17,764
  • 2
  • 43
  • 82
0

The creation of the result must occur inside the function, and not while passing the parameters..
(you do not have access to the function internals while creating the parameters to pass)

var foo = function(options) {
  var options = options || {},
      bar = "bar" + (options.bar || ''),
      baz = "baz" + (options.baz || '');

  return {
    bar: bar,
    baz: baz
  }
};

And calling it like

foo({
  bar: "ret"
});

would yield

>>> { bar: "barret", baz: "baz" }
Gabriele Petrioli
  • 173,972
  • 30
  • 239
  • 291