全局和本地作用域


【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,
});