大网数据广告活动
Web 标准与前端开发

console: context() static method

· 52CE 我爱测

The **`console.context()`** static method creates a new console context: an object with most of the same methods as the `console` object, whose messages are associated with an optional label. This lets you group and filter the messages that come from different parts of your code.

Console API

The console.context() static method creates a new console context: an object with most of the same methods as the console object, whose messages are associated with an optional label. This lets you group and filter the messages that come from different parts of your code.

Syntax

console.context()
console.context(label)

Parameters

  • label
    • : A string used to name the context. Messages logged through the returned object are associated with this name. Defaults to "anonymous".

Return value

A new object that has most of the methods of the console object, such as console/log_static, console/warn_static, console/count_static, and console/time_static. It doesn't have a context() method itself.

Description

Every call to console.context() returns a new, independent console context. Messages logged through a context carry its label, which developer tools can use to identify where a message came from. For example, in the Chrome DevTools, you can type context:myLogger in the filter box to show only the messages logged through a context labeled myLogger.

Each context keeps its own state for counters and timers. This means that console/count_static and console/time_static labels used on one context don't affect the same labels on the global console object or on another context. Calling console/clear_static on a context still clears the whole console.

Just like the methods of console, methods of a console context don't use the value of this, so you can pass them around as unbound functions.

Examples

Creating a named logger

const logger = console.context("myLogger");
logger.log("Hello");
logger.info("World");

Both messages appear in the console like messages logged with console.log() and console.info(). In Chrome DevTools, typing context:myLogger in the console filter box shows only these two messages.

Counters are separate for each context

const a = console.context("A");
const b = console.context("B");

console.count("hits"); // hits: 1
a.count("hits"); // hits: 1
a.count("hits"); // hits: 2
b.count("hits"); // hits: 1
console.count("hits"); // hits: 2

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。