简体   繁体   中英

What is being passed into this 'function(x)'?

I'm having a hard time grasping some finer details of javascript, I have this function function(x) it doesn't seem to be receiving any parameters. Maybe I'm not understanding the Math.sin part. I'm not sure. Any ideas on what is happening?

function makeDerivative( f, deltaX )
     {
        var deriv = function(x) // x isn't designated anywhere
        { 
           return ( f(x + deltaX) - f(x) )/ deltaX;
        }
        return deriv;
    }
    var cos = makeDerivative( Math.sin, 0.000001);
    // cos(0)     ~> 1
    // cos(pi/2)  ~> 0

Update I tried this instead and got NaN, then 15

function addthings(x, y)
    {
                var addition = function(m)
          {
                return( x + y + m);
          }
          return addition;
    }

    var add = addthings(5, 5);
    alert(add());
    alert(add(5));

The outer function returns the inner function, so everything you pass to cos later theoretically is what you pass into the inner function. Imagine calling it like this:

console.log(makeDerivative( Math.sin, 0.000001)(0)); // 1

would output the same as if you're doing it as described

console.log(cos(0)) // 1

as cos is assigned reference to a function (the one that gets returned by makeDerivative ).

要了解代码的工作原理,您必须阅读有关函数javascript函数闭包的更多信息

The other answers touch on the issue, but I'm going to try to get to the core of it.

JavaScript variables are untyped, which means that they can dynamically change what kind of variable they are. On a simple level, this means that var a can be instantiated as an array, and then later assigned as a string on the fly.

But you can also store entire functions within those untyped variables. For example;

var test = 'hey'
console.log(test)      //:: hey
test = function(input){ console.log('inner function: ' + input) }
console.log(test) //:: function(input){ console.log('inner function' + input) }
test() //:: inner function
test('with input') //:: inner function with input

Where //:: _____ represents the output to the console.

So the function you are using returns another dynamic function. You can then call that function in a normal fashion, inputting the value for x when you call it.

Well, you don't really call the function in the code you posted.

The makeDerivative gets reference to Math.sin function and inside it uses it to create reference to function which compute derivation of the passed function (see the f parameter).

In your example this reference is assigned to cos variable. If you called it with ( 0 ) argument, you would get 1 as return value and the argument ( 0 ) would be passed into that deriv function...

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