说我有以下内容:
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"
}
我不知道语法上的正确或最佳方法是什么。
答案 0 :(得分:2)
为什么不呢?
Myobj.prototype.addMovie(somejson) {
this.movies.push( somejson );
}
Myobj.prototype.addGenre(somejson) {
this.genres.push( somejson );
}
Myobj.prototype.pushMovie = Myobj.prototype.addMovie;