undefinedfix
Sign in

A JavaScript function problem

rshibley edited in Thu, 14 Apr 2022
function fun(){
    console.log('foo');
    return {
      fun: function(){
        fun();
      }
    };
}

fun().fun(); // 'foo','foo'

fun().fun().fun(); // 错误:Cannot read property 'fun' of undefined

Why is this the result, JS rookie solution, took a long time did not understand, please advise

6 Replies
thabouti
commented on Thu, 14 Apr 2022

The first line is fun(). Fun() executes fun() first because there are console.log ('foo ') so this is the first print, and then execute the following return to return an object, and then call the fun in the object, and then use the fun () inside the object. Because of the closure, the outermost fun will not be destroyed, and the outermost fun will be executed. All the objects have the second print

The second line of fun (). Fun (). Fun () will output two foos in front of it as above, but fun (). Fun () does not return anything, so it is undefined

kino1
commented on Fri, 15 Apr 2022

After the execution of fun(), an object is returned, which contains a member named fun. Therefore, fun(). Fun() executes function() {fun()} and returns undefined. Therefore, the return of fun(). Fun(). Fun() is wrong

shahonseven
commented on Fri, 15 Apr 2022
function fun(){
    console.log('foo');
    return {
      fun: function(){
        return fun();
      }
    };
}

If you change it to this way, you can loop infinitely. You didn't reverse the return value

fhjcc
commented on Fri, 15 Apr 2022
function fun(){
        console.log('foo');
        return {
            fun: function(){
                fun();
                return this;
            }
        };
    }

    fun().fun(); // 'foo','foo'

    fun().fun().fun();

Fun(). The undefined returned by fun() cannot continue

alex
commented on Fri, 15 Apr 2022

On the first execution, the return value is

fun: function(){
    fun();
}

Fun(). Fun() is a fun property that takes the return value and then executes, which is equivalent to

(function(){
    fun();
})();

Take a look at the function executed this time. It doesn't write return. There is no return value. The return value is undefined. The return value of fun(). Fun() has no fun attribute. Of course, fun(). Fun(). Fun reports an error.

mothman
commented on Fri, 15 Apr 2022

Fu (). Fu (). Fu (): Step 1: Fu (). Fu () execution is

 fun: function(){
                fun();
                return this;
            }

It's him, but no one returns after his execution. If there is no return, the function returns undefined, so undefined has no attribute of fun

lock This question has been locked and the reply function has been disabled.