Reputation:
I am trying to write a method for one object that can create a new instance of a separate object. Is this possible with javascipt?
function Library () {
this.name = "My Library";
this.createShelf = function () {
<some code>
};
}
function Shelf (shelfNumber) {
this.shelfNumber = shelfNumber;
}
var myLib = new Library();
myLib.createShelf();
Is is possible to create a new instance of Shelf by using a method in Library?
Upvotes: 0
Views: 50
Reputation: 83
Another possible usage of Object.create is to clone immutable objects.
function Library () {
this.name = "My Library";
this.createShelf = function () {
<some code>
};
}
var newObject = Object.create(Library());
newObject.createShelf();
Upvotes: 0
Reputation: 59232
Yeah.. you could. Just modify your code to return the Shelf
Object.
function Library () {
this.name = "My Library";
this.createShelf = function (n) {
return new Shelf(n);
}
}
Then you can do this
var myLib = new Library();
var shelf = myLib.createShelf(number);
Upvotes: 2