下面一段javascript代码:

var movie1 = {
  title : "特种部队",
  genre : "Cult Classic",
  rating : 2,
  showtimes : ["3:00pm" ,"7:00pm","11:00pm"],
  totalShows : function () {
    return this.title + "有" +this.showtimes.length +"场";
  }
};
var movie2 = {
  title : "北京遇见西雅图",
  genre : "Love",
  rating : 3,
  showtimes : ["4:00am" ,"5:00pm","11:00pm"],
  totalShows : function () {
    return this.title + "有" +this.showtimes.length +"场";
  }
};

var movie3 = {
  title : "中国合伙人",
  genre: "Bussiness",
  rating: 4,
  showtimes : ['3:00am','4:00pm'],
  totalShows : function () {
    return this.title + "有" +this.showtimes.length +"场";
  }
}

可以看到三个对象有相同的属性和方法,出现重复的代码,特别是totalShows方法,考虑到代码复用和可维护性,习惯OOP的话会想到用继承,设置一个类,然后分别实例化三个对象,可以减少重复代码,在javascript里我们可以使用构造器的写法,我觉得这里有点像工厂方法。代码可以改造如下:

//注意这种写法,用的是function
function Movie (title, genre, rating, showtimes) {
  this.title = title;
  this.genre = genre;
  this.rating = parseInt(rating);
  this.showtimes = showtimes;
  this.totalShows = function () {
    return this.title + "有" +this.showtimes.length +"场";
  }
}
//实例化对象
var movie1 = new Movie("特种部队","Cult Classic",2,["3:00pm","7:00pm","11:00pm"]);
var movie2 = new Movie("北京遇见西雅图","Love",3,["4:00am","5:00pm"]);
//调用方法
alert(movie1.totalShows());
alert(movie2.totalShows());

- EOF -