0

Say I have the following:

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

What I want to be able to do is have some function like:

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

Such that I can go:

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

Or is it better practice to override the array prototype? If so, is it possible to give a prototype a specific array as opposed to all arrays like:

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

I do not know what the syntactically correct or best approach is.

1
  • First idea is fine. No need to add to Array. Commented Jul 12, 2012 at 18:24

1 Answer 1

2

Why not this?

Myobj.prototype.addMovie(somejson) {
   this.movies.push( somejson );
}
Myobj.prototype.addGenre(somejson) {
   this.genres.push( somejson );
}
Myobj.prototype.pushMovie = Myobj.prototype.addMovie;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.