[英]How to extend array or object prototype for a specific javascript object?
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. 我不知道语法上的正确或最佳方法是什么。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.