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

为什么JavaScript对象的成员函数无法访问自身对象的属性?

Why Can't My Object Method Access Its Own Properties?

Hey there! I totally get where you're coming from—this is a super common gotcha when you're starting out with JavaScript objects and methods. Let's unpack what's going on here.

The Root of the Error

Your code is throwing a ReferenceError because when you write street inside the showAddress function, JavaScript is looking for a variable named street in the current function scope (and then the global scope), not the property of the address object. Those are two totally different things!

MDN's note about functions accessing variables from their definition scope is correct—but object properties aren't variables in that scope. They're stored on the object itself, so you need a way to reference the object from inside its method. That's where this comes in.

How to Fix It

In JavaScript, when you call a method on an object (like address.showAddress()), the this keyword inside that method automatically refers to the object that called the method (in this case, address). So you need to prefix each property with this. to tell JavaScript: "Hey, I want the property named street that's on the object this method belongs to."

Here's your corrected code:

const address = { 
  street: "", 
  city: "", 
  zipcode: "", 
  showAddress: function() { 
    return this.street + this.city + this.zipcode; 
  } 
};

Why This Makes Sense

You mentioned you learned that object methods should easily access their own properties—and they can! But JavaScript requires you to explicitly reference the object via this (unlike some other OOP languages that let you skip this step).

Think of it this way: the showAddress function isn't "attached" to the address object in a way that makes the properties automatically available as variables. Instead, this acts as a pointer to the object instance, letting you access its properties and other methods.

If you ever use arrow functions for object methods, you'll run into a different issue (arrow functions don't have their own this), but for regular function methods like yours, this is the right tool for the job.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:13:12