简体   繁体   中英

Why is this undefined when I call a functions property?

Here is my code:

 function myOuterFunction() { myInnerFunction(); var myObject = {say: myInnerFunction.myProperty1, say2: myInnerFunction.myProperty2 }; function myInnerFunction(){ return {myProperty1: "hello", myProperty2: "world" }; } console.log(myObject); } myOuterFunction(); 

Why I am not able to geht the functions property?

I know I could solve this with another variable but why isnt this solution possible?

Thanks

You should store the value of the function before using it.

 function myOuterFunction() { var data = myInnerFunction(); var myObject = { say: data.myProperty1, say2: data.myProperty2 }; function myInnerFunction() { return { myProperty1: "hello", myProperty2: "world" }; } console.log(myObject); } myOuterFunction(); 

your mistakes are 1) try not to use myInnerFunction() inside myOuterFunction(). it's not a good programming practice 2) calling myInnerFunction() does nothing when calling it out in the open. you are not even giving it's return value to a variable. 3) calling myInnerFunction without () doesn't tell javascript that the it is a function

this is the way you should write it

function myOuterFunction() {
    var myObject = {say: myInnerFunction().myProperty1,
                      say2: myInnerFunction().myProperty2
                    };

    console.log(myObject);
}
function myInnerFunction(){

      return {myProperty1: "hello",
              myProperty2: "world"
             };
}
myOuterFunction();

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