> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# CloudScript 中的 ES6 特性

> 在严格模式下使用字符串插值、箭头函数和解构等 ECMAScript 6 特性来编写更简洁的 PlayFab CloudScript 处理程序。

CloudScript 运行时环境支持大多数现代 ECMAScript 6 特性。虽然其中大多数特性只是语法上的技巧,但你可以使用它们来改进和精简你的 CloudScript 代码。

关于 ES6 特性的完整概述可在此[备忘表](https://devhints.io/es6)中找到。

本教程展示了你可以在 CloudScript 中使用的几个技巧。

<Note>
  一些特性需要**严格**模式。将以下代码作为 CloudScript 文件的第一行以启用此模式:`use strict;`
</Note>

## 字符串插值

在为玩家编写消息时,你可能希望使用多行插值字符串。使用*反引号符号*来创建插值字符串。然后,你可以使用 `${ variable }` 语法直接将数据插入字符串。

这可以让你避免字符串拼接,并提高代码的可读性。

<Note>
  反引号字符串是原样字符串,可以是多行。这意味着你必须留意*所有缩进*,因为任何多余的空格/制表符都会被捕获到字符串中。
</Note>

```javascript theme={null}
function sendPushNotification(playerName, prizeAmount, newLevel) {
    let message = `Congratulations ${playerName}!
You have reached level ${newLevel}.
You get ${prizeAmount} coins for your efforts.`;
    // Use message variable and send push notification
    // ...
}
```

## 新方法和箭头函数

ES6 带来了使用箭头运算符 `=>` 定义函数的*新*语法。以下代码片段展示了某些运算符用法的近似翻译。

```javascript theme={null}
// The following snippets:
const add = (a,b) => a+b;

const add = (a,b) => {
    return a+b;
}

// Both translate into something like
function add(a, b) {
    return a+b;
}
```

将该运算符与新的 `Array.findIndex` 方法结合使用,可以通过以下美观、简洁的代码按谓词进行搜索。

```javascript theme={null}
const players = [...]; // Suppose this is an array of Player Profiles

// Search by predicate: find item in 'players' that has 'DisplayName' set to 'Bob':
const bobIndex = players.findIndex(p => p.DisplayName === 'Bob');
```

## 对象赋值

`Object.assign` 方法允许你轻松使用一组新的属性和方法扩展任何对象。

此方法用途广泛,尤其适用于扩展处理程序对象并创建处理程序组。

```javascript theme={null}
let TestHandlers = {
    TestLeaderboards : (args, ctx) => {
        // Test leaderboards code
    },
    TestPrizes : (args, ctx) => {
        // Test prizes code
    }
    // ...
}

let ProductionHandlers = {
    CleanUp : (args, ctx) => {
        // System clean up code
    },
    GrantTournamentAccess : (args, ctx) => {
        // Another useful production code
    }
    // ...
}

// Install both handler groups:
Object.assign(handlers, TestHandlers);
Object.assign(handlers, ProductionHandlers);

// Comment out the group to disable it but keep the relevant code
// Object.assign(handlers, SomeOtherHandlers);
```

这不仅使你可以快速启用和禁用处理程序组,还给你提供了一个可以处理处理程序并将其包装为有用代码(例如异常处理)的地方。

以下代码在前一段代码的基础上添加了自动异常日志记录。作为示例,我们记录了问题(这并不总是有用),但你可以按自己的喜好扩展该行为。

```javascript theme={null}
// Handlers installer wraps the handler to catch error
function installHandlers(handlersObject) {
    for (let property in handlersObject) {
        handlersObject[property] = wrapHandler(handlersObject,property)
    }
    Object.assign(handlers, handlersObject);
}

// Utility
function wrapHandler(obj, key) {
    if (obj.hasOwnProperty(key) && typeof obj[key] === 'function') {
        let original = obj[key]; // Take the original function
        return function() { // return a new function that
            try { // Wraps the original invocation with try
                return original.apply(null,arguments); // Do not forget to pass arguments
            } catch (error) { // If error occurs
                log.error(error); // We log it, but you may want to retry / do something else
                throw error; // Rethrow to keep the original behaviour
            }
        }
    } else { // If property is not a function, ignore it
        return obj[key];
    }
}

// Install handler groups:
installHandlers(TestHandlers);
installHandlers(ProductionHandlers);
```

## Getter

可以使用 “Getter” 将常见的 API 调用封装成语法上更美观的形式。请考虑以下 **Title Data** 状态。

<img src="https://mintcdn.com/microsoft-4404708b/dqv53299jA1M-fNi/images/playfab/live-service-management/service-gateway/automation/cloudscript/tutorials/game-manager-title-data.png?fit=max&auto=format&n=dqv53299jA1M-fNi&q=85&s=0d55c5633f35c7dd1d84ae0259948419" alt="Game Manager - Title Data" width="1366" height="880" data-path="images/playfab/live-service-management/service-gateway/automation/cloudscript/tutorials/game-manager-title-data.png" />

以下代码片段展示了如何从 `TitleData` 检索 `Foo` 和 `Bar` 数据,然后以非常简单的方式使用它们。

```javascript theme={null}
'use strict'

// Define
let App = {
    get TitleData() {
        // Please, consider limiting the query by defining certain keys that you need
        return server.GetTitleData({}).Data;
    },
}

// Use
handlers.TestFooBar = () => {
    // Client code is clean and does not show the fact of calling any functions / making api request
    var titleData = App.TitleData; // Note that this implementation makes an API call every time it's accessed
    log.debug(titleData.Foo);
    log.debug(titleData.Bar);
}
```


## Related topics

- [CloudScript 快速入门](/zh-CN/services/playfab/live-service-management/service-gateway/automation/cloudscript/quickstart.md)
- [在 CloudScript 中处理错误](/zh-CN/services/playfab/live-service-management/service-gateway/automation/cloudscript/handling-errors-in-cloudscript.md)
- [CloudScript](/zh-CN/services/playfab/live-service-management/service-gateway/automation/cloudscript/index.md)
- [编写自定义 CloudScript](/zh-CN/services/playfab/live-service-management/service-gateway/automation/cloudscript/writing-custom-cloudscript.md)
- [通过 CloudScript 修改只读或内部玩家数据](/zh-CN/services/playfab/player-progression/player-data/how-to-modify-read-only-internal-player-data.md)
