简体   繁体   中英

ES6 features Destructuring

by using es6 feature that is destructing , in objects if we made some methods so we can extract that methods also , as property we can , as i try by doing this , please have a look on above code

 let person = { name: "Ravi", favGames: ["cricket", "Badminton", "Tennis"], displayFavGames() { this.favGames.forEach(game => { console.log("My gave game " + game) }) } } person.displayFavGames(); let displayData = ({ name, favGames, displayFavGames }) => { return `My name is ${name} and my cofavourite games is ${displayFavGames}`; } console.log(displayData(person)); 

displayFavGames is a function, so you need to call it.

But since it's a property of the object and uses this , you need to call it using property notation: object.displayFavGames() . You can do that if you destructure the argument, because you don't have a variable that refers to the original object. You can get the argument as a single variable, then use destructuring when initializing local variables.

And if you want to substitute the result of that function, it needs to return a string, not use console.log() .

 let person = { name: "Ravi", favGames: ["cricket", "Badminton", "Tennis"], displayFavGames() { return this.favGames.join("\\n "); } } person.displayFavGames(); let displayData = (p) => { let { name, favGames, displayFavGames } = p; return `My name is ${name} and my cofavourite games are ${p.displayFavGames()}`; } console.log(displayData(person)); 

displayFavGames is a function, while you can destructure it you need to call it which is not seem to achieve what you intend. Instead you can display the actuall favGames values.

let displayData = ({
  name,
  favGames      
}) => {
  return `My name is ${name} and my cofavourite games is 
                    ${favGames.join(",")}`;
}    
console.log(displayData(person));

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