简体   繁体   中英

JavaScript best practice prototype

I have a function in the prototype of the constructor:

function Animal(name) {
  this.name = name
}

Animal.prototype.generateToys = function(numberOfToys) {
  if(numberOfToys == 1) {
    this.createToys();
  } 
  else {
    this.createToys();
  }
}

The createToys still needs to be declared. And that´s where my question is pointing towards. Assuming that generateToys will be the only method that will call createToys() , would it be better to create createToys inside the method generateToys like so:

function Animal(name) {
  this.name = name
}

Animal.prototype.generateToys = function(numberOfToys) {
  if(numberOfToys == 1) {
    this.createToys();
  } 
  else {
    this.createToys();
  }

  function createToys() {
    ...
    ...
    ...
  }
}

Or would you create it as a method(prototype) like the following:

Animal.prototype.createToys = function() {
  ...
  ...
  ...
}

What would be better and why? :)

If you put it inside the generateToys() method, it will be re-declared every single time you call that method, and then be removed from scope when the method completes. Most of the time this isn't what you want, so you'd prefer to create it as a separate method.

That depends on your architecture.

If you plan to have many instances of Animal then adding your method to the prototype is better, otherwise you will be creating a lot of private functions and that is costly (in terms of performance).

declaring the function inside the prototype limits the visibility outside that scope and cause the function to be declared everytime you call Animal.prototype.generateToys() (waste of memory)

Animal.prototype.generateToys = function(numberOfToys) {
   var createToys = function createToys() { 

   }

})

declaring it on the prototype means that each of your instance can call it directly and you will have only one spot in memory with that declaration because the prototype itself it's a single reference shared by all your instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM