【问题标题】:member function is not able to access its member properties? [duplicate]成员函数不能访问其成员属性? [复制]
【发布时间】:2021-11-13 07:53:19
【问题描述】:

我是 javascript 学习对象的新手。我这里创建了一个对象是代码

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

当我输入时:

address.showAddress();

显示错误:

"Uncaught ReferenceError: street is not defined
    at Object.showAddress (index.js:237)
    at <anonymous>:1:

9"

我只是用谷歌搜索了错误,但找不到解决方案。 在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined 我不明白为什么在这个范围内会发生这个错误。在 developer .mozilla.org 上写到,函数可以访问在其定义范围内定义的所有变量和函数。

问题是:

为什么成员函数不能访问它自己对象的属性。 我在 javascript 中研究了 oop 概念,我可以通过它自己的方法轻松访问对象的属性。 我希望问题很清楚。

【问题讨论】:

  • 您可以使用this.street 等...没有this,该函数会尝试在周围范围内查找名为street 的变量,而不是查看调用@ 的对象上的属性987654329@方法
  • “写的是函数可以访问定义在其定义范围内的所有变量和函数” — 正确。没有名为streetcityzipcode 的变量。那些其他的东西是对象属性。
  • 谢谢你的@NickParsons 我明白了。
  • Googling site:stackoverflow.com js ReferenceError in object method referring to properties 发现重复目标。不过,这需要一段时间才能找到,因为它被尝试使用 this,但不在函数中的更常见错误所掩盖......

标签: javascript object javascript-objects


【解决方案1】:

try this

您必须在密钥内部使用“this”。如果我是对的,唯一的方法就是使用“this”。检查图片,如果可行,请写信给我。

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

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-14
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多