我想改进我的 JavaScript 条件代码

I would like to improve my JavaScript condition code

本文关键字:JavaScript 条件 代码 我的      更新时间:2023-09-26

请耐心等待,因为我是JavaScript的新手,我得到了这段代码来尝试改进它,所以任何输入都是有帮助的。我被告知要列出您在代码中看到的一些顾虑或问题。到目前为止,我看到:

使用双等式运算符将对象与字符串进行比较可能不是最佳解决方案

如果数据类型 !=='对象'

另外,请假设假设PeopleFactory是全局定义的。

随意挑选代码。这将是非常有帮助的。谢谢

var Person_D = function Person_D(name) {
  //assume PeopleFactory is defined globally
  //getDetailsAsync returns either null or a record with specific name.
  PeopleFactory.getDetailsAsync(name, function(data) {
    if (typeof data !== 'object') {
      throw new Error('No record found for this individual.');
    }
    this.name = data.name;
    this.age = data.age || 'No age data available.';
    this.eyeColor = data.eyeColor || "This individual's eye color data is not listed.";
    this.height = data.size.height || "No height specified.";
  });
  return this;
}
var personD = new Person_D('Jana');
console.log(personD.name);

您当前状态的问题太宽泛而无法"回答",但是代码中至少有 3 个错误会在所有情况下导致错误。

  1. 代码通过PeopleFactory.getDetailsAsync加载Person_D的属性,这是异步的,但访问personD.name同步的。

  2. 代码使用 this 在回调中分配属性,以便this不再引用Person_D对象。

  3. if(typeof data !=='object')实际上总是会导致true,因为typeof nulltypeof new Object()都会导致"object"。请改用=== null

可能的修复(不假设代码应该如何工作,只是让它在正确的输出下按预期工作(:

var Person_D = function Person_D(name) {
  var self = this;
  //assume PeopleFactory is defined globally
  //getDetailsAsync returns either null or a record with specific name.
  PeopleFactory.getDetailsAsync(name, function(data) {
    if (data === null) {
      throw new Error('No record found for this individual.');
    }
    self.name = data.name;
    self.age = data.age || 'No age data available.';
    self.eyeColor = data.eyeColor || "This individual's eye color data is not listed.";
    self.height = data.size.height || "No height specified.";
    console.log(self.name);
  });
  return this;
}
var personD = new Person_D('Jana');