2017-11-18 113 views
-1

通過使用es6功能是破壞,在對象,如果我們做了一些方法,所以我們可以提取該方法也作爲屬性,我們可以,因爲我嘗試這樣做,請看看上面的代碼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));

+1

我不明白你在尋求什麼幫助。請告訴我們確切的問題是什麼。 – jfriend00

+2

'displayFavGames'是一個函數。你不調用函數,你只是將函數定義插入到模板字符串中。 – Barmar

+1

我看到一個聲明和代碼,但沒有問題。 – apokryfos

回答

2

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));

0

displayFavGames是一個功能,同時可以解構它,你需要把它這似乎並沒有達到你想要的東西。相反,您可以顯示真實的favGames值。

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