【问题标题】:Why can't a method in the instance of my javascript class see a property为什么我的javascript类实例中的方法看不到属性
【发布时间】:2019-05-15 22:06:30
【问题描述】:

在类的构造函数中设置的属性对该类实例中的其他函数不可用

类构造函数将对象作为数据作为其参数。然后将其保存为实例的属性 - 一切都很好。

const form = new Form({
  "name": "John",
  "description": "a good bloke",
  "box_id": 1
});

我可以看到 form.orginalData 是传递的对象,但是当我运行时

form.toString()

我得到一个空对象(在名为 data 的函数中设置)

这是完整的示例

class Form {
  constructor(data) {
    this.orginalData = data
    for (let field in this.orginalData) {
      this[field] = data[field];
    }

  }
  data() {
    let d = {};
    for (let p in this.originalData) {
      d[p] = this[p];
    }

    return d;
  }

  toString() {
    return JSON.stringify(this.data());
  }

}
const form = new Form({
  "name": "John",
  "description": "a good bloke",
  "box_id": 1
});
let message = document.getElementById('message');

form.name = 'Ian';
form.description = 'is a wicked man';

message.innerHTML = form.name + '<br/>';
message.innerHTML += form.description + '<br/>';
message.innerHTML += "orginalData:" + JSON.stringify(form.orginalData) + '<br/>'
message.innerHTML += "<p>BUT if I run form.data() I get </p>"
message.innerHTML += form.toString();
#message {
  border: 1px solid blue;
  padding: 10px;
}

body {
  font-family: Sans-Serif;
}
<h1>
  Class property persistance
</h1>
<p>
  output:
</p>
<div id="message">
  Something went wrong
</div>

我显然遗漏了一些相当基本的东西

【问题讨论】:

  • this[p] 应该是this.originalData[p]
  • 你也可以用let d = Object.assign({}, this.originalData);替换循环
  • 你打错了:this.orginalData 应该是this.originalData

标签: javascript class ecmascript-6


【解决方案1】:

你得到空结果,因为 originalData 与 orginalData

【讨论】:

  • 哦,我的话 - 大脸手掌。轻度阅读障碍的危险。感谢所有看过这篇文章的人。
猜你喜欢
  • 2019-01-03
  • 2020-01-11
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多