如何在对象文字表示法中定义toString方法

时间:2017-09-21 10:36:33

标签: javascript

objects = [{
  name: "The Godfather",
  year: 1972
}, {
  name: "Scarface",
  year: 1983
}, {
  name: "The Godfather II",
  year: 1974
}]; // Apoligies f
alert(objects);

我想这样做,警报返回每部电影的名称,例如为三个电影对象中的每一个定义一个toString方法。有没有办法在objects的数组定义中执行此操作,还是必须单独创建每个对象并将其推送到数组?我更喜欢第一种选择,如下所示:

objects = [{
  name: "The Godfather",
  year: 1972,
  toString: function {
    return name
  }
}, {
  name: "Scarface",
  year: 1983,
  toString: function {
    return name
  }
}, {
  name: "The Godfather II",
  year: 1974,
  toString: function {
    return name
  }
}];
alert(objects);

3 个答案:

答案 0 :(得分:0)

Oluwafemi的解决方案起到了作用:

objects = [{name:"The Godfather", year:1972, toString:function(){return this.name}},{name:"Scarface", year:1982, toString:function(){return this.name}},{name:"The Godfather II", year:1974, toString:function(){return this.name}}];

答案 1 :(得分:0)

您必须将this.name添加到toString功能。



objects = [{
  name: "The Godfather",
  year: 1972,
  toString: function() {
    return this.name
  }
}, {
  name: "Scarface",
  year: 1983,
  toString: function() {
    return this.name
  }
}, {
  name: "The Godfather II",
  year: 1974,
  toString: function() {
    return this.name
  }
}];
alert(objects[1].toString());




答案 2 :(得分:0)

使用function() { return this.name };

更好的是,重复使用相同的功能,而不是每次都创建一个新功能。

function toString() {
  return this.name;
}

objects = [
  {name:"The Godfather", year:1972, toString: toString}
  {name:"Scarface", year:1983, toString: toString},
  {name:"The Godfather II", year:1974, toString: toString}
];
alert(objects);

好多了,编写一个包装函数,返回一个附加到对象原型的toString的新对象。

function Movie(obj) {
  this.name = obj.name;
  this.year = obj.year;
}

Movie.prototype.toString = function() {
  return this.name;
};

objects = [
  new Movie({name:"The Godfather", year:1972}),
  new Movie({name:"Scarface", year:1983}),
  new Movie({name:"The Godfather II", year:1974}),
];
alert(objects);