Question

I am calling a function myFunc() and storing it in a variable myFunction passing 3 as a default argument that will be used to addition.

myFunction get the returned anonymous function with the parameter passed when logging message in the console.

I am also trying to access the method setValue of myFunction to change the original value of 3 to 1

    <script type="text/javascript">
        function myFunc(numPassed){
            var num = numPassed;
            return function(x){
                setValue = function(newVal){
                    num = newVal;
                    return (num + x);
                };
            };
        }
        var myFunction = myFunc(3);
        myFunction.setValue(1);
        console.log(myFunction(4));
    </script>

When I run this, it gives me the error:

Object function (x) has no method 'setValue'

I tried returning the setValue() as well but still the method is not being recognized.

    <script type="text/javascript">
        function myFunc(numPassed){
            var num = numPassed;
            return function(x){
                return setValue = function(newVal){
                    num = newVal;
                    return (num + x);
                };
            };
        }
        var myFunction = myFunc(3);
        myFunction.setValue(1);
        console.log(myFunction(4));
    </script>
Was it helpful?

Solution

If I understand correctly, you'd like myFunc to create a function which will add its input x to the value numPassed, but allow numPassed to be overridden at a later time using setValue. If that's the case, your code should look like this:

function myFunc(numPassed){
    var num = numPassed;
    function add(x) {
        return num + x;
    };
    add.setValue = function(newVal) {
        num = newVal;
    };
    return add;
}

Since myFunc returns add, everything that you want to publicly accessible from the return value must be a property of add.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top