簡體   English   中英

如何用對象文字符號定義toString方法

[英]How to define toString method in object literal notation

 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); 

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}}];

您必須將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()); 

使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM