JavaScript全局对象在函数中返回undefined,调用test函数报错求助
Hey Matthew, let's break down this super common error—it almost always boils down to scope, object references, or how you're invoking your function. Let's walk through the most likely issues and fixes:
1. Your this Context Is Wrong (The #1 Culprit)
Chances are, in your working code, you're accessing the object directly or calling a method that keeps the correct this binding. But when you run your test function, this isn't pointing to your target object anymore.
For example, this code works fine because this refers to obj when you call obj.showX():
const obj = { x: 20, showX() { console.log(this.x); } }; obj.showX(); // Logs 20
But if your test function is defined outside the object and you call it without the right context:
function test() { console.log(this.x); } obj.test = test; // If you call test() instead of obj.test() test(); // `this` points to window (or undefined in strict mode) — no x property exists!
Fixes:
- Bind the function to your object with
bind():const boundTest = test.bind(obj); boundTest(); // Now `this` points to obj - Use an arrow function, which inherits the outer scope's
this:const test = () => { console.log(this.x); }; - Always call the function as a method of your object:
obj.test()
2. You're Not Passing the Object to test
If test expects an object parameter but you're calling it without one (or passing undefined), you'll get this error. For example:
function test(myObj) { console.log(myObj.x); } test(); // myObj is undefined — boom, error!
Fix: Double-check your function call to make sure you're passing the correct object: test(obj);
3. Variable Shadowing Is Hiding Your Object
Sometimes a variable inside test has the same name as your outer object, "shadowing" it and making it undefined inside the function:
const obj = { x: 20 }; function test() { let obj; // This local obj overrides the outer one, starts as undefined console.log(obj.x); } test(); // Error hits here
Fix: Rename the local variable or remove it if it's unnecessary.
Quick Debug Tip
Add a console.log inside test to see exactly what's undefined:
function test() { console.log("Current this:", this); // Check what `this` points to // OR if using a parameter: // console.log("Received object:", myObj); console.log(this.x); }
This will immediately show you whether this is the wrong context, or your object parameter is missing.
内容的提问来源于stack exchange,提问作者Matthew

