简体   繁体   English

如果我有一个分配给函数调用值的变量,如果函数调用的参数发生更改,是否可以更新该变量?

[英]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: 如果我有参数变量,我想传递给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根据我分配给变量parameter1和parameter2的不同值而变化?

functionCallValue is assigned the result (returnvalue) of your function f . functionCallValue分配了函数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. (将调用该函数,将计算出的值并将结果移交给您的变量。)因此, functionCallValue不会自动更新,如果更改参数(这根本没有意义),则需要使用再次调用该函数。更改的参数。

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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