Jessica
Jessica

Reputation: 9830

Setting a default value for object properties

Is it possible to multiple values for one property in objects? Here's what I mean:

// Note: This will give you an error if you try this. It's just an example.
var person = {
    name: "John",
    eyeColor: "blue" | "green"
};

How it should works:
So for eyeColor, the default is blue, but if it's set to green, then it should ignore the blue.

The code above is obviously not executable, but is there something similar I can do to achieve that?

Upvotes: 0

Views: 145

Answers (3)

angelcool.net
angelcool.net

Reputation: 2546

Is it possible to multiple values for one property in objects?

Yes, something like this will do:

var person = {
    name: "John",
    eyeColor: ["blue","green"]
};

That answers your first question.

NOTE: I think your logic is a bit incoherent IMHO.

For your second requirement, I think you're better off writing a setter function:

var person = {
    name: "John",
    eyeColor: "blue",
    setEyeColor:function(color){ this.eyeColor=color;}
};

alert(person.eyeColor);

person.setEyeColor('purple');

alert(person.eyeColor);

Upvotes: 0

Dan Prince
Dan Prince

Reputation: 29989

You can achieve this with a bit of reflection.

I've created a rough implementation of a function which takes an object, the name of a property and a default value. It creates get and set methods for the property in question.

function addDefaultProperty(object, propName, defaultValue) {
  var propValue;

  Object.defineProperty(object, propName, {
    // this method is called when the property is set
    // e.g. object.propName = value
    set: function(value) {
      propValue = value;
    },
    // this method is called when the property is accessed
    // e.g. console.log(object.propName)
    get: function() {
      var hasValue = typeof propValue != 'undefined';
      return hasValue ? propValue : defaultValue;
    }
  });

  return object;
}

Then you can simply create your object however you want and use that method to create properties with default values.

var person = {
  name: "John",
};

addDefaultProperty(person, 'eyeColor', 'blue');

console.log(person.eyeColor); // "blue"

person.eyeColor = "green";
console.log(person.eyeColor); // "green"

person.eyeColor = undefined;
console.log(person.eyeColor); // "blue"

Upvotes: 2

TayTay
TayTay

Reputation: 7170

Here's a very small example of what you're trying to accomplish, and in the same style you're trying to accomplish it... If you don't pass an arg for eyeclr, it will default to 'blue' here.

function newPerson(nm, eyeclr) {
    return {
        name: nm,
        eyeColor: eyeclr || "blue"
    };
}

> newPerson('john')
Object {name: "john", eyeColor: "blue"}

> newPerson('john', 'green')
Object {name: "john", eyeColor: "green"}

Upvotes: 0

Related Questions