Skip to content Skip to sidebar Skip to footer

Passing Variables Values

here is the simple script: function parentFunc() { var x = 15; process(x); } parentFunc(); function process(x) { alert(x); }​ Now when the page loads, parentFunc()

Solution 1:

If I understand your problem correctly, you want to bind a certain argument to process and execute the function later?

You can do this with .bind(). It accepts a context and arguments and creates a new function:

var process_bound = process.bind(null, x);
// later
process_bound();

For an implementation for browsers that don't support .bind(), have a look at the MDN documentation (or see Rocket's comment).


Here is how you should use it:

functionprocess(x) {
    alert(x);
}​

functionparentFunc() {
    var x = 15;
    return process.bind(null, x);
}

var process_bound = parentFunc();

// now bind the event handler to the elementvar element = document.getElementById('someId');
element.onclick = function() {
    process_bound();
    returnfalse;
};

Solution 2:

Use a closure - you can pass a different value to x and create a different frame of reference for each time you call parentscript.

functionparentscript(x) {
process = function(){
    alert(x)
}
return process
}
f = parentscript(23);
f(); //alerts 23

Post a Comment for "Passing Variables Values"