You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode与在线JS编辑器中this关键字输出差异及正确性解析

Why does this behave differently in VS Code vs online editors/tutorials for this JavaScript code?

Let's break down why you're seeing conflicting results—it all boils down to the execution environment your code runs in.

First, let's clarify the expected behavior in different contexts:

When running this code in a traditional global scope (like a browser's top-level or CommonJS module):

  • Variables declared with var get attached to the global object (in browsers, that's window; in Node.js CommonJS, it's globalThis).
  • When you call showFullName() without any context, this defaults to the global object. So this.firstName and this.lastName will pull the global variables "Peter" and "Ally", resulting in Peter Ally.
  • Calling person.showFullName() uses person as the this context, so it correctly outputs Penelope Barrymore.

Why VS Code gives Undefined Undefined for the first call?

Modern VS Code setups (especially when using tools like Code Runner or running Node.js directly) often treat .js files as ES Modules by default. Here's what changes in ES Modules:

  • Variables declared with var (or let/const) at the top level do not get attached to the global object.
  • The top-level this in an ES Module is undefined (instead of pointing to the global object).
  • So when you call showFullName(), this is undefined, and accessing this.firstName/this.lastName returns undefined, hence the output Undefined Undefined.

How to get the tutorial's result in VS Code?

To match the online editor/tutorial behavior, force the code to run in a non-module context:

  • Rename your file from .js to .cjs (CommonJS module format).
  • Or, if you're using a package.json, add "type": "commonjs" to it—this tells Node.js to treat all .js files as CommonJS.

Verdict

Both results are "correct"—they just follow the rules of their respective execution environments. The tutorial/online editor is likely using a global or CommonJS context, while your VS Code setup is using ES Modules.


内容的提问来源于stack exchange,提问作者heeat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:01:55