在下面的代码中,我有两个 Book Collections。一个系列有“Moby Dick”,而另一个系列有“The Firm”。然而,当我看第二个系列时,它也有 Moby Dick。如何创建不共享相同数据的图书?
function Collection () {
var stuff = [];
this.get = function () {
return stuff;
};
this.add = function (item) {
stuff.push(item);
};
}
function Books () {}
Books.prototype = new Collection ();
var myBooks = new Books();
myBooks.add("Moby Dick");
var yourBooks = new Books();
yourBooks.add("The Firm");
console.log(yourBooks.get()); // ["Moby Dick", "The Firm"]
我最终选择了这个:
function Collection () {
var stuff = [];
this.get = function(){
return stuff;
};
this.add = function(item){
stuff.push(item);
};
}
function Books () {
Collection.call(this);
};
Books.prototype = new Collection();
Books.prototype.constructor = Books;
var myBooks = new Books();
myBooks.add("Moby Dick");
var yourBooks = new Books();
yourBooks.add("The Firm");
console.log(myBooks.get());