我怎样才能做到这一点?
var people = Array();
people.push({
name: "John",
height_in_cm : 190,
height_in_inches : this.height_in_cm * 0.39
});
这不起作用。很明显,该对象尚未创建。是否有任何诀窍让这个工作?
答案 0 :(得分:1)
你可以先声明对象然后再推它:
var people = [];
var obj = {
name: "John",
height_in_cm : 190
};
obj.height_in_inches = obj.height_in_cm * .39;
people.push(obj);
根据您的情况,您还可以创建“Person”对象/类:
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