Skip to content

Home > sculp-js > executeInScope

executeInScope() function

在指定作用域中执行代码

Signature:

typescript
export declare function executeInScope(code: string, scope?: Record<string, any>): any;

Parameters

Parameter

Type

Description

code

string

要执行的代码(需包含 return 语句或表达式)

scope

Record<string, any>

(Optional) 作用域对象(键值对形式的变量环境)

Returns:

any

代码执行结果

Example

// 测试用例 1: 基本变量访问 executeInScope("return a + b;", { a: 1, b: 2 }); // 3

// 测试用例 2: 支持复杂表达式和运算 executeInScope( "return Array.from({ length: 3 }, (_, i) => base + i);", { base: 100 } ); // [100, 101, 102]

// 支持外传函数作用域执行 const scope = { $: { fun: { time: { now: function () { return new Date(); }, }, }, }, }; executeInScope("return $.fun.time.now()", scope)

Released under the MIT License.