Cyzanfar
Cyzanfar

Reputation: 7136

Class method in Javascript

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

Upvotes: 0

Views: 119

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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

Upvotes: 3

user4673965
user4673965

Reputation:

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

Upvotes: 0

Related Questions