我想改进我的JavaScript条件代码

时间:2016-10-27 19:15:22

标签: javascript

请耐心等待我,因为我是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);

1 个答案:

答案 0 :(得分:1)

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

  1. 代码加载Person_DPeopleFactory.getDetailsAsync的属性,这是异步的,但同步访问personD.name

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

  3. if(typeof data !=='object')实际上始终会生成true因为typeof nulltypeof new Object()都会产生"object"。请改用=== null

  4. 可能的解决方法(不假设代码应该如何工作,只是让它按正确输出的方式工作):

    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');