Javascript:在创建对象时,如何设置myObject.name之类的东西?

时间:2013-06-26 15:22:42

标签: javascript

我有一个对象:

location = {place1: distance1, place2:distance2};

如何设置location.name = location之类的内容,以便稍后我可以访问“location”字符串?

这样的事情会起作用吗?

location = {
    place1: distance1,
    place2: distance2
    location.name = "location";
}

提前致谢!

2 个答案:

答案 0 :(得分:6)

location = {
    place1: distance1,
    place2: distance2,
    name : "location"
}

答案 1 :(得分:0)

几乎所有东西都可以在js::)

my_location = {
    place1: distance1,
    place2: distance2
};
my_location.name = "location";

alert(my_location.place1 + ' ' + my_location.place2 + ' ' + my_location.name);

另一种方式:

function MyLocation(distance1, distance2){
    this.place1 = distance1;
    this.place2 = distance2;
}
my_location = new MyLocation(dist1, dist2);
my_location.name = "location";
alert(my_location.place1 + ' ' + my_location.place2 + ' ' + my_location.name);