0

How can I achieve this?

var people = Array();

people.push({
    name: "John",
    height_in_cm : 190,
    height_in_inches : this.height_in_cm * 0.39
});

This is not working. It's obvious that the object is not yet created. Are there any tricks on getting this to work?

1
  • You can create a type Person. Commented Feb 27, 2013 at 6:24

1 Answer 1

1

You could just declare the object first and then push it:

var people = [];

var obj = {
  name: "John",
  height_in_cm : 190
};
obj.height_in_inches = obj.height_in_cm * .39;

people.push(obj);

Depending on your case you could also create a "Person" object/class:

var person = (function personModule() {
  function Person(props) {
    this.name = props.name;
    this.height_in_cm = props.height_in_cm;
    this.height_in_inches = this.height_in_cm * .39;
  }

  Person.prototype = {...}; // public methods if necessary

  return function(props) {
    return new Person(props);
  }
}());

var people = [];
people.push(person({ name: 'John', height_in_cm: 190 }));

console.log(people[0].height_in_inches); //=> 74.1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Person class is what I need :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.