如何在JavaScript中挽救对象的未定义属性?

时间:2014-08-07 20:27:23

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

好的,说你有两个对象:gregstacy。他们都是人。 Greg的对象看起来像这样:

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

和Stacy是这样的:

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

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

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

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:1)

您可以使用typeof:

进行显式检查
if (typeof obj.job === "undefined") { ..

或更简单:

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

答案 3 :(得分:0)

错误的架构!

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

或者你打算为每个人写一个自己的静态课程吗?