全局和本地作用域


\Global and local scope

默认求值器提供对全局作用域中存在的任何变量的访问。可以通过将变量分配给与每个 REPLServer 关联的 context 对象来显式地向 REPL 公开变量:

\The default evaluator provides access to any variables that exist in the global scope. It is possible to expose a variable to the REPL explicitly by assigning it to the context object associated with each REPLServer:

import repl from 'node:repl';
const msg = 'message';
repl.start('> ').context.m = msg;const repl = require('node:repl');
const msg = 'message';
repl.start('> ').context.m = msg;

context 对象中的属性在 REPL 中显示为本地:

\Properties in the context object appear as local within the REPL:

$ node repl_test.js
> m
'message' 

默认情况下上下文属性不是只读的。要指定只读的全局变量,则必须使用 Object.defineProperty() 定义上下文属性:

\Context properties are not read-only by default. To specify read-only globals, context properties must be defined using Object.defineProperty():

import repl from 'node:repl';
const msg = 'message';
const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
 configurable: false,
 enumerable: true,
 value: msg,
});const repl = require('node:repl');
const msg = 'message';
const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
 configurable: false,
 enumerable: true,
 value: msg,
});

AltStyle によって変換されたページ (->オリジナル) /