Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Making independent functions work without defining new

I have code like this:

function Food(type) {
  this.type = type;
  this.timesEaten = 0;
}

Food.prototype.eat = function() { // Dependent function
  this.timesEaten++;
}

Food.prototype.pasta = function() { // In-dependent function
  return new Food("pasta")
}

So, I want to be able to use the pasta function without defining a new food, like this:

var pasta = Food.pasta()

Buut, that doesn't work, you have to do like this:

var pasta = new Food().pasta()

Well "Food.pasta()" does work if you set up Food like this:

var Food = {
  pasta: function() {
    return {type: pasta};
  }
}

But then new Food won't work, which means I'll have to use "return {type: pasta}".

I wonder, is there any way to create a Food that can be both dependent and independent?


2 Answers

A method like your .pasta() method that does not operate on any instance data is called a static method. You don't want it on the prototype because the prototype will only be in the lookup chain on an instantiated object (after creating an actual Food object by doing new Food()).

Instead, for a static method you can put it on the constructor function itself like this:

Food.pasta = function() {
    return new Food("pasta");
}

The, you can call it like this:

var pasta = Food.pasta();

It's useful to remember that in javascript, Functions are objects too so they can have properties/methods and when you're looking for a place to put static functions or data that don't belong to a particular instantiated object or need to be called on a particular instantiated object, the Constructor object is often a good place to put them.

like image 119
jfriend00 Avatar answered Sep 20 '26 06:09

jfriend00


function Food(type) {
  this.type = type;
  this.timesEaten = 0;
}

Food.prototype.eat = function() { // Dependent function
  this.timesEaten++;
}

Food.pasta = function() { // In-dependent function
  return new Food("pasta")
}

Food.prototype functions are only available for objects of Food, while for Food.pasta Food is only a namespace object.

Usage:

Food.pasta();
like image 40
bbuecherl Avatar answered Sep 20 '26 06:09

bbuecherl