0

说我有以下内容:

function Myobj = {
   name: "Julia",
   birthdate: "xxxx",
   genres: [],
   movies: [{title: "movie1", rating: 5, genre: "Horror"}, {title: "movie2", rating 3, genre: "Comedy"},{title: "movie3", rating 3, genre: "Comedy"}, {title: "movie4", rating 3, genre: "Comedy"}, {title: "movie5", rating 3, genre: "Horror"}]
}

我想要做的是有一些功能,比如:

Myobj.prototype.pushMovie(somejson) {
   // code to add somejson to "movies", and add the "genre" to the "genres" array
}

这样我就可以走了:

obj1 = new Myobj();
obj1.pushMovie({title: "movie1", rating: 5, genre: "Horror"});

还是重写数组原型是更好的做法?如果是这样,是否可以为原型提供一个特定的数组,而不是所有数组,例如:

Myobj.Array.prototype.pushMovie() {
// code to inherit from regular push, and do some operation to add to "genres"
}

我不知道语法正确或最好的方法是什么。

4

1 回答 1

2

为什么不是这个?

Myobj.prototype.addMovie(somejson) {
   this.movies.push( somejson );
}
Myobj.prototype.addGenre(somejson) {
   this.genres.push( somejson );
}
Myobj.prototype.pushMovie = Myobj.prototype.addMovie;
于 2012-07-12T18:21:54.293 回答