0

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?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Yes this is working. I think I was missing the return keyword. Thank you!
@jacobbarnett glad to have have helped you :)
Is there a way to write the method so that the newly created Shelf becomes a property of the Library object? I'm thinking something like Library.prototype.n
0

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();

Comments

Your Answer

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