如何在 JXA 中定义持久性 属性

How to define a persistent property in JXA

我会在 AppleScript 中编写

property foo: "value"

并且该值将在运行之间保存。我如何在 Javascript 中为自动化执行此操作?

JavaScript for Automation 与 AS 的持久性 属性(和全局值)机制没有直接的平行关系,但它确实有 JSON.stringify()JSON.parse(), 这对于简单的序列化和状态检索很有效。

大概类似于:

(function () {
    'use strict';

    var a = Application.currentApplication(),
        sa = (a.includeStandardAdditions = true, a),
        strPath = sa.pathTo('desktop').toString() + '/persist.json';

    // INITIALISE WITH RECOVERED VALUE || DEFAULT
    var jsonPersist = $.NSString.stringWithContentsOfFile(strPath).js || null,
        persistent = jsonPersist && JSON.parse(jsonPersist) || {
            name: 'perfume',
            value: 'vanilla'
        };
    /*********************************************************/

    // ... MAIN CODE ...

    // recovered or default value
    sa.displayNotification(persistent.value);

    // mutated value
    persistent.value = "Five Spice"

    /*********************************************************/

    // WRAP UP - SERIALISE TO JSON FOR NEXT SESSION
    return $.NSString.alloc.initWithUTF8String(
        JSON.stringify(persistent)
    ).writeToFileAtomically(strPath, true);

})();

(这里有一个更完整的例子:https://github.com/dtinth/JXA-Cookbook/wiki/Examples#properties-which-persist-between-script-runs

或者,对于简单的键值对而不是任意数据结构,请参阅: 关于 JXA 对写入和读取 .plist 的支持