-1

I have a JavaScript function like this:

obj.use('hello', function () {
  // Here I want to access the string 'hello'
});

Is this at all possible, or are there any good workarounds that I can use?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JVG
  • 20,198
  • 47
  • 132
  • 210
  • Not if `use` don't transmits it. But you should learn about javascript closures : http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Sebastien C. Apr 25 '14 at 13:57
  • In this code as is it is not possible, no. If you rewrote that code slightly or if the `use` method does something in particular that would allow such access, then yes. – deceze Apr 25 '14 at 13:57
  • 1
    This question should *not* get closed; he's asking for a workaround, and I aim to provide one in an answer – Dexygen Apr 25 '14 at 14:08
  • 1
    Is `obj` coming from a specific library? If so, it might provide such information. – ForbesLindesay Apr 25 '14 at 14:39
  • 1
    Everybody voting to close, really what is so hard about realizing that obj is an object and use is a method on that object? – Dexygen Apr 25 '14 at 15:03
  • 2
    @GeorgeJempty - You're just making an assumption that the OP has not verified. The question is clearly "Unclear what you're asking" which I and everyone else has chosen. – Jamiec Apr 25 '14 at 15:09
  • 1
    `My answer is based on the fact that your usage indicates use as being a method of the object obj` - thats an assumption - `obj` could be from a library, or not in the OP's control. – Jamiec Apr 25 '14 at 15:14
  • 1
    OK but still why would you choose to vote to close an question you are also answering – Dexygen Apr 25 '14 at 15:15
  • Because thats the best answer I can give at the moment, should it be closed thats fine, should the OP clarify I can improve the answer. – Jamiec Apr 25 '14 at 15:16
  • 1
    Changed fact to assumption in my answer. It's pretty depressing to me to not have much of a chance of gaining reputation after spending 20 minutes on my answer. – Dexygen Apr 25 '14 at 15:19

2 Answers2

1

My answer is based on the assumption that your usage indicates use as being a method of the object obj. In which case the way to achieve your objective is to use the same object to store the first parameter to obj.use.

  var obj = {
    use: function(greeting, fn) {
        obj.greeting = greeting;
        fn();
    }
  }

  obj.use('hello', function () {
    console.log(obj.greeting); //output: 'hello'
  });
Dexygen
  • 12,287
  • 13
  • 80
  • 147
0

// Here I want to access the string 'hello'

Well that's easy, you just store the string in a variable whose scope is accessible inside the method:

var greeting = 'hello';
obj.use(greeting, function () {
    console.log(greeting); // logs "hello"
});
Jamiec
  • 133,658
  • 13
  • 134
  • 193