【问题标题】:How can I rescue an undefined property of an object in JavaScript?如何在 JavaScript 中挽救对象的未定义属性?
【发布时间】:2014-08-07 20:27:23
【问题描述】:

好的,假设您有两个对象:gregstacy。他们都是人。 Greg 的对象如下所示:

var greg = {
  name: "Greg",
  job: "doctor",
  age: 45
}

史黛西是这样的:

var stacy = {
  name: "Stacy",
  age: 42
}

当有人试图访问 Stacy 的 job 属性时,我如何才能在不直接将其作为她的 job 的情况下返回“失业”?我想要一个不使用原型的解决方案,而且我真的宁愿不使用函数来访问对象的所有属性。

仅用于上下文:我将其用于 Ajax 自动加载系统,类似于 Rails 的服务器端系统。

【问题讨论】:

  • if( !stacy.hasOwnProperty("job") ) 返回“失业”;

标签: javascript object error-handling javascript-objects object-properties


【解决方案1】:

我会使用这样的代码...使用具有默认值的构造函数:

function Person(cfg) {
  this.name = cfg.name || "John Q. Public";
  this.job = cfg.job || "Unemployed";
  // EDIT: This will allow for an age of '0' -- a newborn.
  this.age = typeof cfg.age === undefined ? null : cfg.age;
}

var greg = new Person({
  name: "Greg",
  job: "doctor",
  age: 45
});

var stacy = new Person({
  name: "Stacy",
  age: 42
});

console.log(stacy.job);

【讨论】:

    【解决方案2】:

    提取属性时使用||指定默认值。

    var job = person.job || "Unemployed";
    

    但是,这必须在您获得工作的每个地方完成。如果您不想到处重复,则需要使用函数或原型。

    【讨论】:

      【解决方案3】:

      您可以使用 typeof 的显式检查:

      if (typeof obj.job === "undefined") { ..
      

      或更简单地说:

      console.log(obj.job || "Unemployed")
      

      【讨论】:

        【解决方案4】:

        错误的架构!

        function Person(name, job, age) {
            this.name = name ? name : "no name";
            this.job = job ? job : "no job";
            this.age = age ? age : -1:
        }
        var greg = new Person("Greg", "doctor", 45);
        var stacy = new Person("Stacy", null, 42);
        
        console.log(stacy.job);
        

        或者你是否打算为每个人编写一个自己的静态类???

        【讨论】:

        • 啊,好吧,Barmar 是对的。你可以输入 this.name = name || “无名”;还有
        • 而且 Jeremy 的版本更好,因为他正在传递 Objects。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-08
        • 2015-05-19
        相关资源
        最近更新 更多