繁体   English   中英

ES6功能解构

[英]ES6 features Destructuring

通过使用es6中具有破坏性的功能,如果我们做了一些方法,可以在对象中提取这些方法,以便我们也可以提取这些方法,作为属性,正如我尝试这样做的那样,请看一下上面的代码

 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是一个函数,因此需要调用它。

但是,由于它是对象的属性并使用this ,因此您需要使用属性表示法来调用它: object.displayFavGames() 如果您解构参数,则可以执行此操作,因为您没有引用原始对象的变量。 您可以将参数作为单个变量获取,然后在初始化局部变量时使用解构。

而且,如果要替换该函数的结果,则需要返回一个字符串,而不要使用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是一个函数,虽然您可以对其进行displayFavGames ,但需要调用它,但似乎无法实现您的预​​期。 相反,您可以显示实际的favGames值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM