0

Is there such thing as a class method in Javascript?

Example of class method in Ruby

class Item
  def self.show
    puts "Class method show invoked"
  end  
end

Item.show
1

2 Answers 2

3

Like so

function Item() {
   // you can put show method into function
   // Item.show = function () {};   
}

Item.show = function () {
  console.log('Class method show invoked');
}

Item.show();

But better use object literal

var Item = {
  show: function () {
    console.log('Class method show invoked');
  }
};

Item.show();

Sign up to request clarification or add additional context in comments.

2 Comments

What is the most memory efficient?
@Cyzanfar: That's not necessarily the important question. More important is how you want to organize your code. Do you just want to create a "bag of methods/functions"? Then use an object. Do you really want to create instances of a "class" with a class method? Then use a constructor function (aka "class").
0

There's many ways to do this, but my personal favorite is:

function Person(name) { // This is the constructor
    this.name = name;
    this.alive = true;
}

Person.prototype.getName = function() {
    return this.name;
}

myHuman = new Person('Bob')

console.log(myHuman.getName())

5 Comments

Isn't this more of an instance method?
patbaker82, this is a class of which instances can be constructed.
That's not equivalent to the code example in the OP.
humanoid, The getName() function can not be called unless there is an instance of Person. This goes against what the OP was asking for, which was a class method.
True. Sorry about that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.