user4309552
user4309552

Reputation:

Using an object method to instantiate a new object javascript

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

Answers (2)

Siva
Siva

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

Amit Joki
Amit Joki

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

Related Questions