简体   繁体   中英

If I have a variable, assigned to the value of a function call, can that variable be updated if the function call's parameters are changed?

If I have a function, like this:

function f(x,y){
 return x + y;
}

And if I have variables of parameters I want passed to f:

var parameter1;
var parameter2;

If I assign this function call to a variable:

var functionCallValue = f(parameter1,parameter2);

How can I ensure that functionCallValue changes depending on different values I assign to the variable parameter1 and parameter2?

functionCallValue is assigned the result (returnvalue) of your function f . (The function is called, the value calculated and the result handed over to your variable.) Thus functionCallValue does not automatically update, if you change the parameters (which would make no sense at all), you need to call the function again with the altered parameters.

For something like an auto-update you need a closure like this:

var asdf = (function(){

    var param1 = 1;
    var param2 = 2;
    var result = param1+param2;

    function compute(){
        result = param1 + param2;
    }

    return{
        param1:function(x){
           param1 = x;
           compute();
        },
        param2:function(x){
           param2 = x;
           compute();
        },
        result:function(){
           return result;            
        }
    }
})();
console.log(asdf.result()); // logs 3

asdf.param1(3);

console.log(asdf.result());​ // logs 5

Demo

I suppose what you need is a closure .

var servant = function(x, y) { return x + y; };

var param1  = 40;
var param2  = 2;
var master  = function() { return servant(param1, param2) };

var result = master();        // 42.  
param1 = 2;
param2 = 40;
var anotherResult = master(); // still 42, because that's really the answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM