0
說我有以下幾點:如何擴展特定JavaScript對象的數組或對象原型?
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"
}
我不知道語法正確或最好的辦法是什麼。
第一個想法很好。不需要添加到'Array'。 – ThinkingStiff 2012-07-12 18:24:28