简体   繁体   中英

How to get object properties from outside a function?

How do I get the value of name or age from outside the function?

function foo(){
    var person={
        name: "abc",
        company: "pqr",
        age: 25
    };
}
console.log(foo().person.name);

Return person :

 function foo(){ var person = { name: "abc", company: "pqr", age: 25 }; return { person }; } console.log(foo().person.name);

You don't return anything from function, function will return undefined implicitly always. You must return person explicitly (and removed property because I guess you intended person value as is):

 function foo(){ var person = { name: "abc", company: "pqr", age: 25 }; return person; } console.log(foo().name);

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