0

Okay, say you've got two objects: greg and stacy. They're both people. Greg's object looks like this:

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

and Stacy's like this:

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

When someone tries to access Stacy's job property, how can I have that return 'Unemployed' without directly putting that as her job? I'd like a solution that doesn't use prototypes, and I'd really rather not use a function to access all the properties of an object.

Just for context: I'm using this for an Ajax auto-loading system, similar to Rails's server-side one.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Alonessix
  • 82
  • 1
  • 8

4 Answers4

3

I'd use code like this... using a constructor with default values:

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);
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
2

Use || to specify a default value when extracting the property.

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

However, this has to be done in every place where you get the job. If you don't want to have to repeat it all over the place, you need to use a function or prototype.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can use explicit checks with typeof:

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

or more simply:

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

Wrong architecture!

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

Or did you plan to write an own static class for every person???

atmin
  • 370
  • 1
  • 7