3

I'm wondering how I can bind variables to a closure function. Let me use this code:

Please see the code here:

function makeCall(callback) {
var fs = callback.toString();
var stored_callback = eval('(' + fs + ')').bind({ });
stored_callback();
}

function foo(id) {
makeCall(function() {
    console.log(id);
});
}
foo('bar');

After the call of eval, the called function cannot reach the id as it should as a closure.

My question is that before calling the toString, can I somehow retrieve the 'context' of a closure to be stored and retrieved and bind to the call?

5
  • 2
    I'm not quite sure if I understand. id and name are accessible by the function you pass to obj.do, since it is a closure, no matter what this refers to. What is callback in callback.bind( bobInstance );? Maybe you have to provide a better example. Commented Jun 2, 2013 at 21:32
  • You are right, sorry. I hope it is more understandable now. Commented Jun 2, 2013 at 21:49
  • Ok, I might understand what you are trying to say now, but I cannot see the problem. See here: jsfiddle.net/xRLNM. I bind the passed in callback, but it can still access id. Do you want to "change" the id and name values when you bind the callback to a different object? You might have have to provide a jsfiddle.net demo yourself to show the actual issue. Commented Jun 2, 2013 at 22:05
  • Thanks, let me share this to describe my issue: jsfiddle.net/3LfDK/1 Commented Jun 2, 2013 at 22:36
  • Ah. In that case the answer is no. It is not possible to do this. Whatever you are trying to achieve with this, there might be another solution. Commented Jun 2, 2013 at 22:38

1 Answer 1

1

Based on Felix King's answer, it cannot be done. :( Too bad. I just wanted to store calls and executed later for some kind of persistence level. This way an interaction can be made even if the computer restarts or anything... It seems the only way is to not use the embedder parameters from the 'closure', huh? Thanks very much anyway!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.