[javascript] Question when taking function as a factor, foo()()

Asked 2 years ago, Updated 2 years ago, 117 views

Hello. I have a question while studying Closer. The function below does not originally have foo()() and contains annotated parts. When I tried foo()(), it printed well.


var color = 'red';
function foo() {
    var color = 'blue'; // 2
    function bar() {
        console.log(color); // 1
    }
    return bar;
}
foo()(); # blue

// // var baz = foo(); // 3
// // baz(); // 4

Question 1. When you want to call the bar function, which is the internal function of the foo function Do you use parentheses in the same way as foo()()? Then did you name the bar to return it?

Question 2. At first, I wanted to print out the color in the foo function, but when I did the foo.color, undefined came out. Perhaps the internal function was executed in foo()() by returning the internal function with return bar...?

Like the bar function, color Is there any other way to get the value of the color variable in the function if you create an instance like bar baz=foo()?

Thank you for reading my question! :)

javascript function parameter

2022-09-22 08:34

1 Answers

Question 1. When you want to call the bar function, which is the internal function of the foo function, do you use parentheses in the same way as foo()()? Then did you name the bar to return it?

No, it's not.
The bar function inside foo can be called simply because foo returns bar, and foo()baz() is the same operation that used to do baz( foo()() calls the foo function, obtains a return value, and then calls it again.It just means .

Question 2. At first, I wanted to print the color in the foo function, but when I did the foo.color, undefined came out. Maybe the internal function was executed in foo()() by returning the internal function with a return bar, right?

var color is a regional variable that cannot be accessed, such as foo.color.

function foo() { ... }
foo.color = "blue";
console.log(foo.color); // "blue"

You can fake it like this, but it's not the right way.
The only way to obtain the region variable color of a simple function is to return color.

The behavior you want to do can be implemented as a prototype, which is often used in object orientation.

function Foo() {
    this.color = "blue";
}
Foo.prototype.bar = function() {
    console.log(this.color);
}

var foo = new Foo();
console.log(foo.color); // "blue"
foo.bar(); // "blue"


2022-09-22 08:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.